import axios, { InternalAxiosRequestConfig } from 'axios';
import Cookies from 'js-cookie';
import { navigateTo } from './navigationHandler';

const isProd = process.env.NODE_ENV === 'production';

// Dev  → /api-proxy  (Next.js rewrites → avoids CORS)
// Prod → NEXT_PUBLIC_API_BASE_URL (direct call)
const baseURL = isProd
  ? process.env.NEXT_PUBLIC_API_BASE_URL
  : '/api-proxy';

const apiClient = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Api-Token': process.env.NEXT_PUBLIC_API_TOKEN ?? '',
  },
});

// Inject auth token + user_id into every POST
// Guest fallback: user_id = "0" (API rejects empty string with 400)
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userId = Cookies.get("user_id") ?? "0";

    if (config.method === "post" && config.data) {
      if (config.data instanceof FormData) {
        if (!config.data.has("user_id")) {
          config.data.append("user_id", userId);
        }
      } else if (typeof config.data === "object" && !Array.isArray(config.data)) {
        if (!("user_id" in config.data)) {
          config.data = { ...config.data, user_id: userId };
        }
      }
    }

    // Attach Bearer token only for authenticated users (user_id != "0")
    const token = Cookies.get("auth_token");
    if (token && userId !== "0" && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor
// 1. API uses body-level status (200 = success, 400+ = error) — normalise to a rejection
// 2. HTTP 401 → clear auth and redirect to login
apiClient.interceptors.response.use(
  (response) => {
    const bodyStatus = response.data?.status;
    if (typeof bodyStatus === 'number' && bodyStatus >= 400) {
      return Promise.reject(new Error(response.data?.message ?? 'API error'));
    }
    return response;
  },
  (error) => {
    if (error.response?.status === 401) {
      Cookies.remove('auth_token');
      Cookies.remove('user_id');
      navigateTo('/auth/login');
    }
    return Promise.reject(error);
  },
);

export default apiClient;
