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");

    const { days } = await req.json();
    const daysCount = days || 30;

    // Cache key
    const cacheKey = `demand_curve_${daysCount}`;
    const { data: cached } = await supabase
      .from("analytics_cache")
      .select("*")
      .eq("cache_key", cacheKey)
      .gte("expires_at", new Date().toISOString())
      .single();

    if (cached) {
      return new Response(
        JSON.stringify({ success: true, data: cached.data, cached: true }),
        { headers: { ...corsHeaders, "Content-Type": "application/json" } }
      );
    }

    // Simular curva de demanda (em produção, buscar do external)
    const curve = [];
    for (let i = 0; i < daysCount; i++) {
      const date = new Date();
      date.setDate(date.getDate() - (daysCount - i));
      curve.push({
        date: date.toISOString().split("T")[0],
        appointments: Math.floor(Math.random() * 50) + 20,
      });
    }

    // Salvar cache
    const expiresAt = new Date();
    expiresAt.setHours(expiresAt.getHours() + 6);
    await supabase.from("analytics_cache").upsert({
      cache_key: cacheKey,
      data: curve,
      expires_at: expiresAt.toISOString(),
      created_at: new Date().toISOString(),
    });

    const data = curve;

    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" },
      }
    );
  }
});
