import { validateExternalAuth } from "../_shared/auth.ts";

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers":
    "authorization, x-client-info, apikey, content-type",
};

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

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

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

    // Limpar cache expirado
    const { error: deleteError } = await supabase
      .from("analytics_cache")
      .delete()
      .lt("expires_at", new Date().toISOString());

    if (deleteError) throw deleteError;

    // Recalcular doctor_stats
    const { data: doctors } = await supabase
      .from("doctor_stats")
      .select("external_doctor_id")
      .limit(100);

    let rebuilt = 0;
    for (const doctor of doctors || []) {
      // Em produção: recalcular stats do external Supabase
      await supabase
        .from("doctor_stats")
        .update({ updated_at: new Date().toISOString() })
        .eq("external_doctor_id", doctor.external_doctor_id);
      rebuilt++;
    }

    const data = {
      message: "Cache rebuilt",
      stats_rebuilt: rebuilt,
      cache_cleared: true,
      timestamp: new Date().toISOString(),
    };

    return new Response(JSON.stringify({ success: true, data }), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (error: any) {
    return new Response(
      JSON.stringify({ success: false, error: error.message }),
      {
        status: 400,
        headers: { ...corsHeaders, "Content-Type": "application/json" },
      }
    );
  }
});
