// MÓDULO 1: AUTH / PERFIS - /user/info
import { corsHeaders } from "../_shared/cors.ts";
import { validateExternalAuth } from "../_shared/auth.ts";

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  try {
    const { user, ownSupabase } = await validateExternalAuth(req);
    const supabase = ownSupabase;

    // Buscar role e permissões
    const { data: userRole } = await supabase
      .from("user_roles")
      .select("role")
      .eq("user_id", user.id)
      .single();

    // Buscar preferências
    const { data: preferences } = await supabase
      .from("user_preferences")
      .select("*")
      .eq("user_id", user.id)
      .single();

    return new Response(
      JSON.stringify({
        success: true,
        data: {
          user: {
            id: user.id,
            email: user.email,
            phone: user.phone,
            created_at: user.created_at,
            ...user.user_metadata,
          },
          role: userRole?.role || "patient",
          permissions: getRolePermissions(userRole?.role || "patient"),
          preferences: preferences || getDefaultPreferences(),
        },
      }),
      { headers: { ...corsHeaders, "Content-Type": "application/json" } }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      {
        status: 400,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  }
});

function getRolePermissions(role: string) {
  const permissions: Record<string, string[]> = {
    admin: ["*"],
    doctor: [
      "read:patients",
      "write:reports",
      "read:appointments",
      "write:appointments",
    ],
    secretary: [
      "read:patients",
      "read:appointments",
      "write:appointments",
      "read:reports",
    ],
    patient: ["read:own_data", "write:own_appointments"],
  };
  return permissions[role] || permissions.patient;
}

function getDefaultPreferences() {
  return {
    dark_mode: false,
    high_contrast: false,
    font_size: "medium",
    dyslexia_font: false,
    notifications_enabled: true,
    language: "pt-BR",
  };
}
