import axios, { type AxiosInstance } from "axios";

/**
 * All microservices run behind Traefik API Gateway on port 80.
 * Traefik routes by path prefix:
 *   /api/v1/products, /api/v1/categories → catalog-service
 *   /api/v1/inventory, /api/v1/stock     → inventory-service
 *   /api/v1/kitchen                       → fnb-engine
 *   /api/v1/orders                        → order-service
 */
const GATEWAY_URL = process.env.API_GATEWAY_URL || "http://localhost/api/v1";

function createClient(baseURL: string): AxiosInstance {
  const client = axios.create({
    baseURL,
    timeout: 30_000,
    headers: { "Content-Type": "application/json" },
  });

  // Attach Bearer token
  client.interceptors.request.use((config) => {
    const token = process.env.API_TOKEN;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  });

  // Strip auth headers from error objects to prevent token leakage
  client.interceptors.response.use(
    (response) => response,
    (error) => {
      if (axios.isAxiosError(error) && error.config?.headers) {
        delete error.config.headers.Authorization;
      }
      return Promise.reject(error);
    }
  );

  return client;
}

// Single gateway client — Traefik routes by path prefix
const gateway = createClient(GATEWAY_URL);

// Export aliases (all point to same gateway)
export const catalogApi = gateway;
export const inventoryApi = gateway;
export const fnbApi = gateway;
export const orderApi = gateway;

export const DEFAULT_SHOP_ID =
  process.env.DEFAULT_SHOP_ID || "e1f392af-fe95-4c7f-8656-5b74ad5fd0a9";
