import axios, { AxiosInstance } from "axios";
import { tokenStore } from "./token";

export function attachAuthInterceptors(client: AxiosInstance) {
  client.interceptors.request.use((config) => {
    const token = tokenStore.get();
    if (token) {
      if (!config.headers) {
          (config as any).headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  });

  client.interceptors.response.use(
    (res) => res,
    (error) => {
      if (error.response?.status === 401) {
        tokenStore.clear();
      }
      return Promise.reject(error);
    }
  );
}

/**
 * Factory for app APIs that need auth
 */
export function createApiClient(baseURL: string): AxiosInstance {
  const client = axios.create({
    baseURL,
    headers: { "Content-Type": "application/json" },
  });

  attachAuthInterceptors(client);
  return client;
}
