import axios, { AxiosError, HttpStatusCode } from 'axios';
import { TOKEN_KEY } from '../consts';
import { getLocale } from '../i18n';

const BASE_PATH = '/api';
export const API = axios.create({
  baseURL: BASE_PATH,
  withCredentials: false,
});

API.interceptors.request.use(
  function (config) {
    try {
      const token = localStorage.getItem(TOKEN_KEY) || '';
      const locale = getLocale();
      if (config && config['headers']) {
        config['headers']['Authorization'] = token.replaceAll('"', '');
        config['headers']['Accept-Language'] =
          locale === 'en' ? 'en-US' : 'vi-VN';
      }
    } catch (_) {}

    return config;
  },
  function (error) {
    return Promise.reject(error);
  },
);

API.interceptors.response.use(
  function (value) {
    return value;
  },
  function onError(error) {
    if (
      error instanceof AxiosError &&
      [HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden].includes(
        error.response?.status,
      )
    ) {
      localStorage.removeItem(TOKEN_KEY);
      window.dispatchEvent(new Event('local-storage'));
    }
    return Promise.reject(error);
  },
);
