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 checks = {
      database: "ok",
      external_api: "ok",
      cache: "ok",
      notifications: "ok",
    };

    // Testar conexão com DB
    try {
      const { error } = await supabase
        .from("user_actions")
        .select("id")
        .limit(1);
      if (error) checks.database = "error";
    } catch {
      checks.database = "error";
    }

    // Verificar cache
    try {
      const { data: cache } = await supabase
        .from("analytics_cache")
        .select("id")
        .limit(1);
      if (!cache) checks.cache = "warning";
    } catch {
      checks.cache = "error";
    }

    const allOk = Object.values(checks).every((v) => v === "ok");
    const data = {
      status: allOk ? "healthy" : "degraded",
      checks,
      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" },
      }
    );
  }
});
