import axios from "axios";
import { BACKEND_BASE } from "../config";

type TokenSupplier = () => string | null;
type UnauthorizedHandler = () => void;

let tokenSupplier: TokenSupplier = () => null;
let unauthorizedHandler: UnauthorizedHandler | null = null;

export const apiClient = axios.create({
  baseURL: `${BACKEND_BASE}api/v1`,
  withCredentials: true,
});

apiClient.interceptors.request.use((config) => {
  const token = tokenSupplier();

  if (token) {
    config.headers = config.headers ?? {};
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});

apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      unauthorizedHandler?.();
    }

    return Promise.reject(error);
  }
);

export function configureApiAuth(options: {
  tokenProvider: TokenSupplier;
  onUnauthorized?: UnauthorizedHandler;
}) {
  tokenSupplier = options.tokenProvider;
  unauthorizedHandler = options.onUnauthorized ?? null;
}
