import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

// Helper para validar JWT e extrair user_id
export async function validateAuth(
  req: Request
): Promise<{ userId: string; role: string } | null> {
  const authHeader = req.headers.get("Authorization");

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    return null;
  }

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

  // Validar token com Supabase
  const MY_URL =
    Deno.env.get("SUPABASE_URL") || "https://etblfypcxxtvvuqjkrgd.supabase.co";
  const MY_KEY =
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ||
    Deno.env.get("SUPABASE_SERVICE_KEY")!;

  const supabase = createClient(MY_URL, MY_KEY);

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

  if (error || !user) {
    return null;
  }

  // Buscar role do usuário
  const { data: userRole } = await supabase
    .from("user_roles")
    .select("role")
    .eq("user_id", user.id)
    .single();

  return {
    userId: user.id,
    role: userRole?.role || "patient",
  };
}

// Helper para verificar permissões
export function hasPermission(
  userRole: string,
  requiredRoles: string[]
): boolean {
  return requiredRoles.includes(userRole);
}
