import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { getFreshToken, getToken } from './auth';

const apiClient = axios.create({
  baseURL: process.env.REACT_APP_API_BASE_URL,
  headers: {}
});

export type APIErrorType = AxiosResponse;

export async function request(auth = false, options: AxiosRequestConfig) {
  if (auth) {
    const accessToken = await getToken();
    options.headers = { ...options.headers, Authorization: `Bearer ${accessToken}` };
  }

  try {
    return (await apiClient(options)).data;
  } catch (error) {
    if (!axios.isAxiosError(error)) throw error;
    if (!auth || error.response?.status !== 401) throw error.response;
    const accessToken = await getFreshToken();
    options.headers = { ...options.headers, Authorization: `Bearer ${accessToken}` };

    try {
      return (await apiClient(options)).data;
    } catch (error) {
      if (!axios.isAxiosError(error)) throw error;
      throw error.response;
    }
  }
}
