import intervalPromise from 'interval-promise';
import { useSessionStorage } from '@vueuse/core';
import { STORAGE_KEYS } from '@/constant/storage';
import delay from 'delay';
import store from '@/vue/store';
import { openSellerHome } from '@/api/shopee/utils';
import i18n from '@/vue/i18n';
import { loggerVue } from '@/plugins/logger';

const serviceWorkerKeepAlive = () => {
  const port = chrome.runtime.connect({ name: 'keepAlive' });
  port.postMessage({ ping: true, from: 'Popup Option' });
};

export const checkShopeeApiValid = async () => {
  const isAllValid = await store.dispatch('ShopeeSellerFetchAuth');

  if (!isAllValid) {
    store.dispatch('PushMessageError', i18n.t('SHOPEE_MAY_BE_NO_LOGIN'));
    openSellerHome();
  }

  return isAllValid;
};

const taskShopeeFlashsale = () => {
  const TASK_FLASHSALE_LASTEST = 15 * 60 * 1000;
  const taskFlashsaleLastest = useSessionStorage(STORAGE_KEYS.SESSION_STORAGE.SHOPEE_FLASHSALE_TASK_LASTEST, 0);
  const timeLeft = Date.now() - TASK_FLASHSALE_LASTEST;

  if (taskFlashsaleLastest.value >= timeLeft) {
    return;
  }

  const shopId = store.getters.getShopeeShopId;
  const shopAuthed = store.getters.getShopeeSellerAuthed;

  if (!(shopId && shopAuthed)) {
    return;
  }

  store.dispatch('RunShopeeFlashsaleAutoScheduler');
  store.dispatch('RunShopeeFlashsaleAutoCampaign');
  taskFlashsaleLastest.value = Date.now();
};

export const initStore = async () => {
  await store.dispatch('UserStore');

  if (store.getters.getIsAuthed) {
    await store.dispatch('UserFetch');
  }

  store.dispatch('FetchExtensionInfo').catch((error) => {
    loggerVue.error({ msg: 'APP_INFO_ERROR', error });
  });

  store.dispatch('AppIndentify').catch((error) => {
    loggerVue.error({ msg: 'APP_INDENTIFY_ERROR', error });
  });

  delay(1000)
    .then(() => store.dispatch('ShopeeSellerInit'))
    .catch((error) => {
      loggerVue.error({ msg: 'SHOP_INIT_ERROR', error });
    });

  delay(2000)
    .then(taskShopeeFlashsale)
    .then(() => {
      intervalPromise(taskShopeeFlashsale, 5 * 60 * 1000, {
        iterations: Infinity,
        stopOnError: true,
      });
    })
    .catch((error) => {
      loggerVue.error({ msg: 'TASK_FLASHSALE_SCHEDULER_ERROR', error });
    });

  chrome.runtime.sendMessage({ type: 'wakeUp' }).catch(() => {});
  serviceWorkerKeepAlive();
  setInterval(serviceWorkerKeepAlive, 5000);
};
