import { createMiddleware } from "@tanstack/react-start";
import { getRequest } from "@tanstack/react-start/server";
import { createClient } from "@supabase/supabase-js";

export const requireExtSupabaseAuth = createMiddleware({ type: "function" }).server(
  async ({ next }) => {
    const url = process.env.EXTERNAL_SUPABASE_URL;
    const anon = process.env.EXTERNAL_SUPABASE_ANON_KEY;
    if (!url || !anon) {
      throw new Error("Missing EXTERNAL_SUPABASE_URL / EXTERNAL_SUPABASE_ANON_KEY");
    }

    const request = getRequest();
    const authHeader = request?.headers?.get("authorization");
    if (!authHeader?.startsWith("Bearer ")) {
      throw new Error("Unauthorized: No bearer token");
    }
    const token = authHeader.replace("Bearer ", "");

    const supabase = createClient(url, anon, {
      global: { headers: { Authorization: `Bearer ${token}` } },
      auth: { persistSession: false, autoRefreshToken: false },
    });

    const { data, error } = await supabase.auth.getUser(token);
    if (error || !data?.user) throw new Error("Unauthorized: Invalid token");

    return next({
      context: { supabase, userId: data.user.id, user: data.user },
    });
  },
);