"use client";

import { useEffect } from "react";
import { deleteCookie } from "cookies-next";

// Endpoints où un 401 est une réponse métier normale (mauvais identifiants),
// pas une session expirée : ne doit pas déclencher la déconnexion globale.
const EXCLUDED_PATHS = ["/api/proxy/auth/login", "/api/proxy/auth/register"];

/**
 * Aucun helper HTTP partagé n'existe dans l'admin (chaque fichier de src/lib
 * fait son propre fetch), donc un intercepteur 401 centralisé passe par un
 * patch de window.fetch plutôt que par une réécriture de tous les appels.
 */
export function ApiUnauthorizedWatcher() {
  useEffect(() => {
    const originalFetch = window.fetch;

    window.fetch = async (...args: Parameters<typeof fetch>) => {
      const response = await originalFetch(...args);

      if (response.status === 401) {
        const input = args[0];
        const requestUrl = typeof input === "string" ? input : (input as Request)?.url ?? "";
        const isProxyCall = requestUrl.includes("/api/proxy/");
        const isExcluded = EXCLUDED_PATHS.some((path) => requestUrl.includes(path));

        if (isProxyCall && !isExcluded && window.location.pathname !== "/login") {
          deleteCookie("authToken");
          window.location.href = "/login";
        }
      }

      return response;
    };

    return () => {
      window.fetch = originalFetch;
    };
  }, []);

  return null;
}
