import { supabase } from "@/lib/supabase";

/**
 * Authenticated fetch wrapper.
 * Automatically injects `Authorization: Bearer <token>` from the active
 * Supabase session. Falls back to an unauthenticated request if no session
 * exists (lets public endpoints still work normally).
 *
 * Drop-in replacement for `fetch` — same signature, same return value.
 */
export async function authFetch(
  input: RequestInfo | URL,
  init: RequestInit = {}
): Promise<Response> {
  const {
    data: { session },
  } = await supabase.auth.getSession();

  const headers = new Headers(init.headers);

  if (session?.access_token) {
    headers.set("Authorization", `Bearer ${session.access_token}`);
  }

  if (init.body && typeof init.body === "string" && !headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  return fetch(input, { ...init, headers });
}
