import { createClient } from "@supabase/supabase-js";

/**
 * Verifies the request comes from an authenticated admin user.
 * Extracts the JWT from the Authorization header, validates it,
 * and checks the user exists in the admin_users table.
 *
 * Returns the authenticated user's ID.
 * Throws an error with status code if auth fails.
 */
export async function verifyAdmin(req: Request): Promise<string> {
  const authHeader = req.headers.get("Authorization");
  if (!authHeader?.startsWith("Bearer ")) {
    throw new AuthError("Missing or invalid Authorization header", 401);
  }

  const token = authHeader.replace("Bearer ", "");

  const url = Deno.env.get("SUPABASE_URL");
  const anonKey = Deno.env.get("SUPABASE_ANON_KEY");

  if (!url || !anonKey) {
    throw new AuthError("Missing SUPABASE_URL or SUPABASE_ANON_KEY", 500);
  }

  // Create a user-scoped client with the provided JWT
  const supabase = createClient(url, anonKey, {
    global: { headers: { Authorization: `Bearer ${token}` } },
    auth: { persistSession: false },
  });

  const {
    data: { user },
    error: userError,
  } = await supabase.auth.getUser();

  if (userError || !user) {
    throw new AuthError("Invalid or expired token", 401);
  }

  // Verify user is an admin
  const { data: adminUser, error: adminError } = await supabase
    .from("admin_users")
    .select("id")
    .eq("id", user.id)
    .single();

  if (adminError || !adminUser) {
    throw new AuthError("User is not an admin", 403);
  }

  return user.id;
}

export class AuthError extends Error {
  status: number;
  constructor(message: string, status: number) {
    super(message);
    this.name = "AuthError";
    this.status = status;
  }
}
