import '@/types/Shopee/Shop/Index';
import axios from 'axios';
import queryString from 'query-string';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';
import { SHOPEE_DOMAIN_SELLER } from '@/config/api';
import { getKeyCookie, setKeyCookie, getAllCookies } from '@/browser/cookies';
import { readyPostUrlShopeeSeller } from '@/bridge/shopee/api';
import { getBaseHeader } from '@/api/shopee/getter';

const VERSION = '3.1.0';
const SPC_CDS_VER = '2';

/**
 *
 * @returns {BrowserCookieStore[]}
 */
export const getShopeeSellerCookies = () => getAllCookies(SHOPEE_DOMAIN_SELLER);
export const getShopeeSellerCds = async () => getKeyCookie('SPC_CDS', SHOPEE_DOMAIN_SELLER);

/**
 *
 * @param {string} SPC_CDS
 * @returns
 */
export const setShopeeSellerCds = async (SPC_CDS) => setKeyCookie('SPC_CDS', SPC_CDS, SHOPEE_DOMAIN_SELLER);

const getSellerPayload = async () => {
  const SPC_CDS = await getShopeeSellerCds();

  return {
    version: VERSION,
    SPC_CDS,
    SPC_CDS_VER,
  };
};

export const apiShopeeSeller = axios.create({
  baseURL: SHOPEE_DOMAIN_SELLER,
  headers: getBaseHeader(),
  responseType: 'json',
  adapter: fetchAdapter,
});

apiShopeeSeller.interceptors.response.use((response) => response.data);
apiShopeeSeller.interceptors.request.use(async (request) => {
  request.headers = {
    ...getBaseHeader(),
    ...(request.headers || {}),
  };
  request.params = {
    ...(await getSellerPayload()),
    ...(request.params || {}),
  };

  return request;
});

export const validShopeeApiSeller = async () => {
  const SPC_CDS = await getShopeeSellerCds();

  return !!SPC_CDS;
};

export const sellerFetchPost = async (uri, payload) => {
  const params = await getSellerPayload();

  const url = queryString.stringifyUrl({
    url: `${SHOPEE_DOMAIN_SELLER}${uri}`,
    query: params,
  });

  return readyPostUrlShopeeSeller(url, payload);
};
