import axios, {
  AxiosError,
  AxiosInstance,
  InternalAxiosRequestConfig,
} from 'axios';
import {
  getAccessToken,
  handleTokenRefresh,
} from '../login/utils/tokenRefresh';

const AUTH_API_URL = process.env.NEXT_PUBLIC_AUTH_API_URL;

export const profileApi: AxiosInstance = axios.create({
  baseURL: AUTH_API_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
});

const addToken = (config: InternalAxiosRequestConfig) => {
  if (globalThis.window !== undefined) {
    const token = getAccessToken();
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }
  return config;
};

profileApi.interceptors.request.use(addToken);

const handleResponseError = async (error: AxiosError) => {
  const originalRequest = error.config as InternalAxiosRequestConfig & {
    _retry?: boolean;
  };

  if (!originalRequest) {
    throw error;
  }

  return handleTokenRefresh(error, originalRequest, profileApi);
};

profileApi.interceptors.response.use(
  (response) => response,
  handleResponseError
);
