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

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

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

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