import axios, { AxiosError, AxiosResponse } from 'axios';
import {
  BASE_API_URL,
  ErrorRequest,
  StorageAccessToken,
  handleLogout,
  // StorageAccessToken
} from '@pos/base';

axios.defaults.baseURL = BASE_API_URL;
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.post['Accept'] = '*/*';

axios.interceptors.request.use(async (request: any) => {
  const token = await StorageAccessToken.get();
  // const token = authorization;
  if (token) {
    request.headers.authorization = token;
  }

  return request;
});

axios.interceptors.response.use(
  (response) => {
    const data = response.data;
    const status = response.status;
    return { data, status } as any;
  },
  (e) => {
    const errorStatus = e.response?.status;
    if (errorStatus === 401) {
      const [, currentPath] = window.location.href.split('app/');
      handleLogout('/app/' + currentPath);
    }

    const error = e as AxiosError<any>;
    const errorResponse: AxiosResponse = error?.response as AxiosResponse;
    const errorData = errorResponse?.data;
    const status = errorResponse?.status;
    const message = errorData?.message ?? errorData;
    return Promise.reject(new ErrorRequest(errorData, message, status));
  },
);
