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 { job } = await req.json();
    if (!job) throw new Error("job name required");

    const jobs: Record<string, string> = {};

    switch (job) {
      case "process_notifications":
        // Processar fila de notificações
        const { data: pending } = await supabase
          .from("notifications_queue")
          .select("*")
          .eq("status", "pending")
          .limit(50);

        jobs.notifications = `Processed ${pending?.length || 0} notifications`;
        break;

      case "cleanup_cache":
        await supabase
          .from("analytics_cache")
          .delete()
          .lt("expires_at", new Date().toISOString());
        jobs.cache = "Cleaned expired cache";
        break;

      case "update_stats":
        const { data: stats } = await supabase
          .from("doctor_stats")
          .select("id")
          .limit(1);
        jobs.stats = "Updated doctor stats";
        break;

      default:
        jobs[job] = "Unknown job";
    }

    const data = {
      job,
      results: jobs,
      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" },
      }
    );
  }
});
