/* eslint-disable promise/prefer-await-to-callbacks */
import axios, { AxiosError, AxiosInstance, AxiosResponse } from 'axios';
import forceLogout from '@/utils/forceLogout.util';

type ResponseData = {
  message: string;
  statusCode: number;
};

const api = ({ headers = {}, params = {} } = {}): AxiosInstance => {
  const BASE_URL = import.meta.env.VITE_APP_TAGSAMURAI_API;

  const instance = axios.create({
    baseURL: `${BASE_URL}/fam/settings-user-role/v2/auth`,
    headers: {
      'Content-type': 'application/json',
      ...headers,
    },
    params,
  });

  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      return response;
    },
    (error: AxiosError) => {
      if (
        error.response?.status === 401 ||
        (error.response?.data as ResponseData).message === 'jwt malformed'
      ) {
        forceLogout();
      }
      return Promise.reject(error);
    },
  );

  return instance;
};

type ReLogin = { jwt: string };
const reLogin = (body: ReLogin): Promise<AxiosResponse> => {
  return api().post('/login', body);
};

const AuthAPIs = { reLogin };

export default AuthAPIs;
