import delay from 'delay';
import lodash from 'lodash';
import { getShopeeProfileClient, getShopeeSpcfValue } from '@/api/shopee/client/shop';
import {
  shopeeShopCreate,
  shopeeShopUpdateShopId,
  shopeeShopRemoveShopId,
  shopeeShopGetShopId,
} from '@/api/autoshopee/shopee/shop';
import { getShopeeSellerCookies, getShopeeSellerCds, setShopeeSellerCds } from '@/api/shopee/seller/init';
import {
  getShopeSellerLogisticList,
  getShopeSellerWarehouseList,
  getShopeeSellerLogin,
  getShopeeSellerInfo,
  getShopeeSellerFallbackInfo,
} from '@/api/shopee/seller';
import { validateShopeeApiAuthed } from '@/api/shopee/utils';
import { getTabIsCaptcha } from '@/bridge/shopee/api';
import i18n from '@/vue/i18n';
import { loggerShopee } from '@/plugins/logger';

const SHOP_INIT_INTERVAL = 5 * 60 * 1000;

const AUTH_RETRY_MAX = 6;
const AUTH_RETRY_DELAY = 2000;

const validateShopeeApiAuthedRetry = async () => {
  let isAuthed = await validateShopeeApiAuthed();
  let attempt = 0;

  while (!isAuthed && attempt < AUTH_RETRY_MAX) {
    await delay(AUTH_RETRY_DELAY);
    isAuthed = await validateShopeeApiAuthed();
    attempt += 1;
  }

  return isAuthed;
};

export const actions = {
  async ShopeeSellerSync({ state }) {
    /** @type {StoreShopeeShop} */
    const shopState = state;

    if (!(shopState.ref && shopState.id)) {
      return null;
    }

    const shopRef = state.ref;

    const cookies = await getShopeeSellerCookies();

    const payload = {
      cookies,
      shopId: shopState.id.toString(),
    };

    return shopeeShopUpdateShopId(shopRef, payload);
  },
  async ShopeeSellerUnSync({ state }) {
    /** @type {StoreShopeeShop} */
    const shopState = state;

    if (!(shopState.ref && shopState.id)) {
      return null;
    }

    const shopRef = shopState.ref;
    state.ref = '';

    return shopeeShopRemoveShopId(shopRef);
  },
  ShopeeSellerLogisticSet({ commit }, value) {
    commit('SET_SHOPEE_SELLER_LOGISTIC', value);
  },
  ShopeeSellerWarehouseSet({ commit }, value) {
    commit('SET_SHOPEE_SELLER_WAREHOUSE', value);
  },
  async ShopeeSellerConnect({ dispatch }) {
    const cookies = await getShopeeSellerCookies();

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

    const profileClient = await getShopeeProfileClient();

    if (profileClient && profileClient.username) {
      payloadCreate.shopId = profileClient.shopid || profileClient.shop_id;
      payloadCreate.name = profileClient.username;
      payloadCreate.username = profileClient.username;
      payloadCreate.phone = profileClient.phone;
      payloadCreate.email = profileClient.email;
    } else {
      const sellerFallback = await getShopeeSellerFallbackInfo();

      if (sellerFallback) {
        payloadCreate.shopId = sellerFallback.shopId;
        payloadCreate.name = sellerFallback.shopName;
        payloadCreate.username = sellerFallback.username;
      }
    }

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

    const shopCreate = await shopeeShopCreate(payloadCreate);

    dispatch('ShopeeSellerInit', true);

    return shopCreate;
  },
  async ShopeeSellerInit({ state, commit, dispatch }, isForceSync = false) {
    /** @type {StoreShopeeShop} */
    const shopState = state;

    if (isForceSync) {
      shopState.isInited = false;
    }

    if (shopState.isInited) {
      return false;
    }

    let sellerId = 0;
    const sellerInfo = await getShopeeSellerInfo();

    if (sellerInfo) {
      commit('SET_SHOPEE_SELLER_INFO', sellerInfo);
      sellerId = sellerInfo.shopid || sellerInfo.shop_id;
    } else {
      const sellerFallback = await getShopeeSellerFallbackInfo();
      sellerId = sellerFallback.shopId;
      commit('SET_SHOPEE_SELLER_SHOP_ID', sellerId);
      commit('SET_SHOPEE_SELLER_SHOP_NAME', sellerFallback.shopName);
    }

    dispatch('ShopeeSellerConfig').catch((error) => {
      loggerShopee.error({
        msg: 'SHOP_FETCH_CONFIG_ERROR',
        error,
      });
    });

    if (isForceSync) {
      const shopId = sellerId.toString();

      if (!lodash.isObject(shopState.lastestSync)) {
        shopState.lastestSync = {};
      }

      const lastestFetch = Number(shopState.lastestSync[shopId]) || 0;

      const difftime = (Date.now() - lastestFetch) || 0;

      const isReSync = !lastestFetch || difftime >= SHOP_INIT_INTERVAL;

      if (isForceSync || isReSync) {
        const shopSync = (await shopeeShopGetShopId(shopId)).data;

        if (shopSync) {
          await commit('SET_SHOPEE_SELLER_SYNC', shopSync);

          dispatch('ShopeeSellerSync').catch((error) => {
            loggerShopee.error({
              msg: 'SHOP_UPDATE_SYNC_ERROR',
              error,
            });
          });

          shopState.lastestSync[shopId] = Date.now();
        } else {
          await commit('SET_SHOPEE_SELLER_UNSYNC');
        }
      }
    }

    return true;
  },
  async ShopeeSellerConfig({ state }) {
    /** @type {StoreShopeeShop} */
    const shopState = state;

    if (shopState.isFetched) {
      return false;
    }

    const shopId = shopState.id;
    const listLogistic = await getShopeSellerLogisticList(shopId);
    const listWarehouse = await getShopeSellerWarehouseList(shopId);

    // Logistic
    const logisticPriority = listLogistic.filter(({ enabled, is_mask_channel }) => enabled && is_mask_channel);
    const logisticActive = listLogistic.filter(({ enabled, is_mask_channel }) => enabled && !is_mask_channel);

    shopState.shopLogistic.list = (logisticPriority && logisticPriority.length ? logisticPriority || [] : logisticActive || []).map(({ channel_id, name }) => {
      return {
        name,
        id: channel_id,
        value: channel_id.toString(),
        express: name.includes('Hỏa Tốc'),
        disabled: false,
      };
    });

    if (!shopState.shopLogistic.selected.length) {
      shopState.shopLogistic.selected = shopState.shopLogistic.list.map((item) => item.value);
    }

    // Warehouse
    shopState.shopWarehouse.list = listWarehouse.map((item) => {
      const extendLabel = item.in_holiday_mode ? ' (Off)' : '';

      return {
        name: item.warehouse_name + extendLabel,
        value: item.location_id,
        id: item.warehouse_id,
        disabled: item.in_holiday_mode,
      };
    });

    if (!shopState.shopWarehouse.selected.length) {
      shopState.shopWarehouse.selected = shopState.shopWarehouse.list.map((item) => item.value);
    }

    shopState.isFetched = true;

    return true;
  },
  async ShopeeSellerFetchAuth({ state, dispatch, commit }) {
    /** @type {StoreShopeeShop} */
    const shopState = state;

    let SPC_CDS = await getShopeeSellerCds();

    if (SPC_CDS) {
      commit('SET_SHOPEE_SELLER_SPC_CDS', SPC_CDS);
    }

    if (!SPC_CDS && shopState.spccds) {
      SPC_CDS = shopState.spccds;
      await setShopeeSellerCds(SPC_CDS);
    }

    if (SPC_CDS) {
      await getShopeeSellerLogin(SPC_CDS);
    }

    const captchaCheck = async () => {
      shopState.isCaptcha = await getTabIsCaptcha();

      if (shopState.isCaptcha) {
        dispatch('PushMessageError', i18n.t('SHOPEE_CAPTCHA_DETECT_RESLOVER'));
      }
    };

    shopState.isAuthed = await validateShopeeApiAuthedRetry();

    captchaCheck();
    setInterval(captchaCheck, 10000);

    const SPC_F = await getShopeeSpcfValue();

    if (SPC_F) {
      commit('SET_SHOPEE_SELLER_SPC_F', SPC_F);
    }

    return shopState.isAuthed;
  },
};
