import '@/types/Tiktok/Seller/Get';
import axios from 'axios';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';
import { TIKTOK_DOMAIN_SELLER } from '@/config/api';
import { storageTiktokShopId } from '@/plugins/storage/items';
import { getKeyCookie } from '@/browser/cookies';

const CSRF_COOKIE_NAME = 'passport_csrf_token';
const CSRF_COOKIE_NAME_DEFAULT = 'passport_csrf_token_default';
const CSRF_HEADER_NAME = 'x-secsdk-csrf-token';
const CSRF_METHODS = ['post', 'put', 'delete', 'patch'];

const APP_ID = 4068;
const APP_NAME = 'i18n_ecom_shop';
const LOCALE = 'vi-VN';
const LANGUAGE = 'vi-VN';
const REGION = 'VN';
const TIMEZONE_NAME = 'Asia/Ho_Chi_Minh';

/**
 *
 * @returns {Promise<string>}
 */
export const getTiktokSellerId = async () => storageTiktokShopId.getValue();

/**
 *
 * @returns {Promise<TiktokSellerBaseParams>}
 */
export const getTiktokSellerBaseParams = async () => {
  const sellerId = await getTiktokSellerId();

  return {
    aid: APP_ID,
    app_name: APP_NAME,
    locale: LOCALE,
    language: LANGUAGE,
    oec_seller_id: sellerId,
    seller_id: sellerId,
    oec_region: REGION,
    timezone_name: TIMEZONE_NAME,
    device_platform: 'web',
    browser_platform: 'Win32',
    browser_language: 'en-US',
    browser_online: true,
    cookie_enabled: true,
    PIGEON_BIZ_TYPE: 1,
  };
};

/**
 *
 * @returns {Promise<string>}
 */
export const getTiktokSellerCsrfToken = async () => {
  const token = await getKeyCookie(CSRF_COOKIE_NAME, TIKTOK_DOMAIN_SELLER);

  if (token) {
    return token;
  }

  return getKeyCookie(CSRF_COOKIE_NAME_DEFAULT, TIKTOK_DOMAIN_SELLER);
};

export const apiTiktokSeller = axios.create({
  baseURL: TIKTOK_DOMAIN_SELLER,
  responseType: 'json',
  adapter: fetchAdapter,
});

apiTiktokSeller.interceptors.response.use((response) => response.data);
apiTiktokSeller.interceptors.request.use(async (request) => {
  request.params = {
    ...(await getTiktokSellerBaseParams()),
    ...(request.params || {}),
  };

  const method = String(request.method || '').toLowerCase();

  if (CSRF_METHODS.includes(method)) {
    const csrfToken = await getTiktokSellerCsrfToken();

    if (csrfToken) {
      request.headers = {
        ...(request.headers || {}),
        [CSRF_HEADER_NAME]: csrfToken,
      };
    }
  }

  return request;
});
