import { getUserInfo } from '@/api/autoshopee/user';
import { loggerBackground } from '@/plugins/logger';
import { browserAlarms } from '@/browser/api';
import { shopeeFlashsaleSync, shopeeSellerAuthSync } from './task';
import { getShopeeSellerFallbackInfo } from '@/api/shopee/seller';
import { ShopeeShopIdentify } from '@background/store/shop';

const configTask = {
  flashsale: {
    name: 'task:shopee:flashsale',
    periodInMinutes: 15,
  },
  seller: {
    name: 'task:shopee:seller',
    periodInMinutes: 10,
  },
};

export const shopeeShopIdentify = async () => {
  const shopInfo = await getShopeeSellerFallbackInfo();

  if (!shopInfo.shopId || !shopInfo.username) {
    return null;
  }

  ShopeeShopIdentify.setShopId(shopInfo.shopId);
  ShopeeShopIdentify.setShopName(shopInfo.username);

  return shopInfo;
};

export const shopeeService = async () => {
  const { data: userInfo } = await getUserInfo();

  if (!(userInfo && userInfo.username)) {
    return false;
  }

  shopeeFlashsaleSync().catch((error) => {
    loggerBackground.error({
      msg: 'SHOPEE_BACKGROUND_FLASHSALE_SYNC_ERROR',
      error,
    });
  });

  shopeeSellerAuthSync().catch((error) => {
    loggerBackground.error({
      msg: 'SHOPEE_BACKGROUND_SYNC_DATA_ERROR',
      error,
    });
  });

  browserAlarms.create(configTask.flashsale.name, { periodInMinutes: configTask.flashsale.periodInMinutes });
  browserAlarms.create(configTask.seller.name, { periodInMinutes: configTask.seller.periodInMinutes });

  browserAlarms.onAlarm.addListener((alarm) => {
    if (alarm.name === configTask.flashsale.name) {
      shopeeFlashsaleSync().catch((error) => {
        loggerBackground.error({
          msg: 'SHOPEE_BACKGROUND_FLASHSALE_SYNC_ERROR',
          error,
        });
      });
    }

    if (alarm.name === configTask.seller.name) {
      shopeeSellerAuthSync().catch((error) => {
        loggerBackground.error({
          msg: 'SHOPEE_BACKGROUND_SYNC_DATA_ERROR',
          error,
        });
      });
    }
  });
};
