// ═══════════════════════════════════════════════════
//  lib/api/http.ts
// ═══════════════════════════════════════════════════

export const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

export async function fetchApi<T>(
  url: string,
  options?: RequestInit,
): Promise<T> {
  try {
    // ✅ Read token from sessionStorage for API calls
    const token =
      typeof window !== "undefined"
        ? localStorage.getItem("access_token") ||
        sessionStorage.getItem("access_token")
        : null;

    console.log("🔍 API Request:", {
      url,
      method: options?.method || "GET",
      hasToken: !!token,
    });

    const res = await fetch(url, {
      ...options,
      credentials: "include", // ✅ add this — sends cookie automatically
      headers: {
        "Content-Type": "application/json",
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
        ...(options?.headers || {}),
      },
    });

    // ── 401 → session expired ──
    if (res.status === 401) {
      if (typeof window !== "undefined") {
        localStorage.removeItem("access_token"); // ✅ add
        localStorage.removeItem("user"); // ✅ add
        sessionStorage.removeItem("access_token");
        sessionStorage.removeItem("user");

        if (typeof window !== "undefined" &&
          !window.location.pathname.startsWith("/client")) {
          window.location.href = "/login";
        }
      }
      throw new Error("Session expired. Please login again.");
    }

    // ── 403 → no permission ──
    if (res.status === 403) {
      const errorData = await res.json().catch(() => ({}));
      throw new Error(
        errorData.message ||
        "You don't have permission to perform this action.",
      );
    }

    if (!res.ok) {
      const text = await res.text();
      let message = text;
      try {
        const json = JSON.parse(text);
        message = Array.isArray(json.message)
          ? json.message.join(", ")
          : json.message || text;
      } catch { }
      throw new Error(message || "Network response was not ok");
    }

    // ── 204 No Content ──
    if (res.status === 204) return undefined as unknown as T;

    const contentType = res.headers.get("content-type") || "";
    if (!contentType.includes("application/json")) {
      const text = await res.text();
      return text as unknown as T;
    }

    const text = await res.text();
    if (!text) return undefined as unknown as T;
    return JSON.parse(text) as T;
  } catch (error: any) {
    if (error instanceof TypeError && error.message === "Failed to fetch") {
      throw new Error(
        "Unable to connect to the server. Please ensure the backend is running.",
      );
    }
    throw error;
  }
}
