"use client";

import { LOGIN_SESSION_EXPIRED_HREF } from "@/app/utils/authToken";

/**
 * Client-side fetch that adds Bearer token from localStorage and redirects
 * to /login?session=expired on 401 or 403 (session timeout / unauthorized).
 * Use this for all authenticated API requests so session expiry is handled consistently.
 */
export async function clientAuthFetch(
  input: RequestInfo | URL,
  init?: RequestInit
): Promise<Response> {
  const token =
    typeof window !== "undefined" ? localStorage.getItem("accessToken") : null;
  const headers = new Headers(init?.headers);
  if (token) {
    headers.set("Authorization", `Bearer ${token}`);
  }

  const response = await fetch(input, { ...init, headers });

  if (response.status === 401 || response.status === 403) {
    if (typeof window !== "undefined") {
      console.warn(`Auth error ${response.status} → redirecting to login`);
      window.location.href = LOGIN_SESSION_EXPIRED_HREF;
    }
  }

  return response;
}
