import { storageShopeeFlashsaleCampaignAuto, storageShopeeFlashsaleSchedulerAuto } from '@/plugins/storage/items';
import { createScheduleFlashsaleFromCampaignShopId } from '@/service/shopee/flashsale/campaign';
import { createFlashsaleFromSchedulerShopId } from '@/service/shopee/flashsale/scheduler';
import { getShopeeSellerFallbackInfo, getShopeeSellerLogin } from '@/api/shopee/seller';
import { getShopeeSellerCookies } from '@/api/shopee/seller/init';
import { shopeeShopSyncFromBackground } from '@/api/autoshopee/shopee/shop';
import { imageUrl } from '@/adapter/shopee/render/index';
import { enCryptApiData } from '@/lib/utils/crypt';

export const shopeeSellerAuthSync = async () => {
  const cookies = await getShopeeSellerCookies();

  const payloadCreate = {
    shopId: '',
    name: '',
    username: '',
    phone: '',
    email: '',
    cookies,
    image: '',
  };

  const sellerLogin = await getShopeeSellerLogin();

  if (sellerLogin && sellerLogin.shopid) {
    payloadCreate.shopId = sellerLogin.shopid.toString();
    payloadCreate.name = sellerLogin.username;
    payloadCreate.username = sellerLogin.username;
    payloadCreate.phone = sellerLogin.phone;
    payloadCreate.email = sellerLogin.email;
    payloadCreate.image = imageUrl(sellerLogin.portrait);
  } else {
    const sellerInfo = await getShopeeSellerFallbackInfo().catch(() => null);

    if (!sellerInfo) {
      return null;
    }

    payloadCreate.shopId = sellerInfo.shopId.toString();
    payloadCreate.name = sellerInfo.shopName;
    payloadCreate.username = sellerInfo.username;
  }

  if (!payloadCreate.shopId) {
    return null;
  }

  const payloadString = enCryptApiData(JSON.stringify(payloadCreate));

  return shopeeShopSyncFromBackground({ payload: payloadString });
};

export const shopeeFlashsaleSync = async () => {
  const [isAutoCampaign, isAutoScheduler] = await Promise.all([
    storageShopeeFlashsaleCampaignAuto.getValue(),
    storageShopeeFlashsaleSchedulerAuto.getValue(),
  ]);

  const getSeller = await getShopeeSellerFallbackInfo().catch(() => null);

  if (!getSeller) {
    return null;
  }

  const shopId = getSeller.shopId.toString();

  if (isAutoCampaign) {
    await createScheduleFlashsaleFromCampaignShopId(shopId);
  }

  if (isAutoScheduler) {
    await createFlashsaleFromSchedulerShopId(shopId);
  }

  return true;
};
