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

interface FetchOptions extends RequestInit {
  skipAuth?: boolean;
}

export async function apiFetch(endpoint: string, options: FetchOptions = {}) {
  const { skipAuth, ...fetchOptions } = options;

  // ✅ Add this before headers:
  const token =
    typeof window !== "undefined"
      ? localStorage.getItem("access_token") ||
      sessionStorage.getItem("access_token")
      : null;

  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}), // ✅ add this line
    ...(fetchOptions.headers as Record<string, string>),
  };

  const res = await fetch(`${BASE_URL}${endpoint}`, {
    ...fetchOptions,
    headers,
    credentials: "include", // ✅ sends httpOnly cookie automatically
  });

  if (res.status === 401) {
    if (typeof window !== "undefined" &&
      !window.location.pathname.startsWith("/client")) {
      window.location.href = "/login";
    }
    return;
  }

  if (!res.ok) {
    const error = await res.json().catch(() => ({}));
    throw new Error(error.message || `API error: ${res.status}`);
  }

  return res.json();
}
