// Client-only: inject Supabase access token into server-fn requests so
// that middlewares like requireSupabaseAuth see an Authorization header.
import { supabase } from "./client";

if (typeof window !== "undefined" && !(window as any).__lovableServerFnFetchPatched) {
  (window as any).__lovableServerFnFetchPatched = true;
  const origFetch = window.fetch.bind(window);
  window.fetch = async (input: RequestInfo | URL, init: RequestInit = {}) => {
    try {
      const url =
        typeof input === "string"
          ? input
          : input instanceof URL
            ? input.toString()
            : input.url;
      if (url && url.includes("/_serverFn/")) {
        const { data } = await supabase.auth.getSession();
        const token = data.session?.access_token;
        if (token) {
          const headers = new Headers(
            init.headers || (input instanceof Request ? input.headers : undefined)
          );
          if (!headers.has("authorization")) {
            headers.set("authorization", `Bearer ${token}`);
          }
          init = { ...init, headers };
        }
      }
    } catch {
      // ignore; fall through to original fetch
    }
    return origFetch(input as any, init);
  };
}

export {};
