import axios from 'axios';
import { configAppApi } from '@/config/api';
import { configApp } from '@/config/app';
import { userSetting } from '@/plugins/setting';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';
import { bridgeFetchApiAutoshopee } from '@/bridge/content/background';

const { apiUrl, cmsUrl } = configAppApi;
const { verNumber } = configApp;

export { apiUrl, verNumber, cmsUrl };

const getHeader = async () => {
  let userToken = userSetting.userToken.get();

  if (!userToken) {
    userToken = await userSetting.userToken.getSync();
  }

  if (userToken) {
    return {
      Authorization: `Bearer ${userToken}`,
      source: 'extension',
      ref: 'extension',
      version: verNumber,
    };
  }
  return {

  };
};

export const apiApp = axios.create({
  adapter: fetchAdapter,
  baseURL: apiUrl,
  responseType: 'json',
  timeout: 60000,
});

export const apiPublic = axios.create({
  adapter: fetchAdapter,
  baseURL: apiUrl,
  responseType: 'json',
  timeout: 60000,
});

export const apiCms = axios.create({
  adapter: fetchAdapter,
  responseType: 'json',
  timeout: 60000,
  baseURL: cmsUrl,
});

export const apiBridge = async ({
  url, method, body, params,
}) => {
  const headers = await getHeader();

  return bridgeFetchApiAutoshopee({
    baseURL: apiUrl,
    headers,
    params: params || {},
    url,
    body: body || {},
    method,
  });
};

apiApp.interceptors.request.use(async (request) => {
  request.headers = await getHeader();
  return request;
});

apiApp.interceptors.response.use((response) => response.data);
apiPublic.interceptors.response.use((response) => response.data);
apiCms.interceptors.response.use((response) => response.data);
