import { shopeeSetting } from '@/plugins/setting';
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();
    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([
    shopeeSetting.shopeeFlashsaleCampaignAuto.getSync(),
    shopeeSetting.shopeeFlashsaleSchedulerAuto.getSync(),
  ]);

  const getSeller = await getShopeeSellerFallbackInfo();

  const shopId = getSeller.shopId.toString();

  if (!shopId) {
    return null;
  }

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

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

  return true;
};
