import '@/types/Shopee/Shop/Index';
import { SHOPEE_DOMAIN_HOME } from '@/config/api';
import { getKeyCookie, getAllCookies } from '@/browser/cookies';
import { apiShopeeClient } from '@/api/shopee/client/init';
import getShopeeShopId from './get';
import getShopeeShopByUsername from './user';
import shopeeSearchShopId from './search';

export { getShopeeShopId, getShopeeShopByUsername, shopeeSearchShopId };

export const getShopeeSpcfValue = () => getKeyCookie('SPC_F', SHOPEE_DOMAIN_HOME);

/**
 *
 * @returns {BrowserCookieStore[]}
 */
export const getShopeeClientCookies = () => getAllCookies(SHOPEE_DOMAIN_HOME);

export const validShopeeApiClient = async () => {
  const listCookies = await getShopeeClientCookies();

  const [SPC_U, SPC_SC_UD, SPC_STK, SPC_IA] = ['SPC_U', 'SPC_SC_UD', 'SPC_STK', 'SPC_IA'].map((item) => {
    const match = listCookies.find(({ name }) => name === item);
    return match ? match.value : '';
  });

  if (SPC_U && !isNaN(SPC_U)) {
    return true;
  }

  if (SPC_SC_UD && !isNaN(SPC_SC_UD)) {
    return true;
  }

  if (SPC_STK && SPC_STK !== '-') {
    return true;
  }

  if (SPC_IA && SPC_IA === '1') {
    return true;
  }

  return false;
};

/**
 *
 * @returns {Promise<ShopeeShopProfile>}
 */

export const getShopeeProfileClient = async () => {
  try {
    const result = await apiShopeeClient.get('/api/v2/user/profile/get/');

    if (!result.data) {
      return null;
    }

    result.data.shop_id = result.data.shop_id || result.data.shopid;
    result.data.user_id = result.data.userid || result.data.userid;

    return result.data;
  } catch (error) {
    return null;
  }
};
