import axios from "axios";
import { AUTH_COOKIE_NAME } from "@/lib/constants/auth";
import { ROUTES } from "@/lib/constants/routes";
import { getLanguageCookie } from "@/lib/i18n/cookie";
import { DEFAULT_LANGUAGE, LANGUAGE_HEADER_KEY } from "@/lib/i18n/config";

const api = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:3000",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
    "ngrok-skip-browser-warning": "true",
  },
});

// ─── Request Interceptor ──────────────────────────────────────────────────────
// Attach JWT from cookie on every outgoing request
api.interceptors.request.use((config) => {
  if (typeof document !== "undefined") {
    const match = document.cookie
      .split("; ")
      .find((row) => row.startsWith(`${AUTH_COOKIE_NAME}=`));
    const token = match ? match.split("=")[1] : null;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }
  // Attach the current language (cookie = single source of truth) so the backend
  // can localize responses. Refetched automatically on toggle via invalidateQueries.
  config.headers[LANGUAGE_HEADER_KEY] = getLanguageCookie() ?? DEFAULT_LANGUAGE;
  return config;
});

// ─── Response Interceptor ─────────────────────────────────────────────────────
// On 401, clear cookie and redirect to login
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (
      error.response?.status === 401 &&
      typeof window !== "undefined" &&
      !window.location.pathname.startsWith("/auth")
    ) {
      // Clear cookie
      document.cookie = `${AUTH_COOKIE_NAME}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`;
      window.location.href = ROUTES.AUTH.LOGIN;
    }
    return Promise.reject(error);
  },
);

export default api;
