import axios from "axios";
import { getToken, clearStoredAuth } from "./storage.js";
import { redirectToHseLogin } from "./loginRedirect.js";

export function createApiClient(options = {}) {
  const {
    baseURL = "",
    onUnauthorized = redirectToHseLogin,
    timeout = 60000,
  } = options;

  const client = axios.create({ baseURL, timeout });

  client.interceptors.request.use((config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  });

  client.interceptors.response.use(
    (res) => res,
    (err) => {
      if (err.response?.status === 401) {
        clearStoredAuth();
        onUnauthorized();
      }
      return Promise.reject(err);
    }
  );

  return client;
}
