// MÓDULO 1: AUTH / PERFIS - /user/update-preferences
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 authHeader = req.headers.get("Authorization");
    if (!authHeader) throw new Error("Missing authorization header");

    const supabase = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_ANON_KEY")!,
      { global: { headers: { Authorization: authHeader } } }
    );

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

    const body = await req.json();
    const { preferences } = body;

    // Validar preferências
    const validPreferences = {
      dark_mode: preferences.dark_mode ?? false,
      high_contrast: preferences.high_contrast ?? false,
      font_size: preferences.font_size || "medium",
      dyslexia_font: preferences.dyslexia_font ?? false,
      notifications_enabled: preferences.notifications_enabled ?? true,
      language: preferences.language || "pt-BR",
      timezone: preferences.timezone || "America/Sao_Paulo",
    };

    // Upsert preferências
    const { data, error } = await supabase
      .from("user_preferences")
      .upsert({
        user_id: user.id,
        ...validPreferences,
        updated_at: new Date().toISOString(),
      })
      .select()
      .single();

    if (error) throw error;

    return new Response(JSON.stringify({ success: true, data }), {
      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" },
      }
    );
  }
});
