import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { externalRest } from "../../lib/externalSupabase.ts";
import { mydb } from "../../lib/mySupabase.ts";
import { corsHeaders, jsonResponse, errorResponse } from "../../lib/utils.ts";
import { validateAuth, hasPermission } from "../../lib/auth.ts";
import { appointmentFiltersSchema } from "../../lib/validation.ts";

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

  try {
    // Validar autenticação
    const auth = await validateAuth(req);
    if (!auth) {
      return errorResponse("Não autorizado", 401);
    }

    // Registrar acesso em audit_log
    await mydb.from("audit_log").insert({
      user_id: auth.userId,
      action: "list_appointments",
      target_type: "appointments",
    });

    // Aceita GET normal ou POST com method GET
    let patientId: string | null = null;

    if (req.method === "GET") {
      const url = new URL(req.url);
      patientId = url.searchParams.get("patient_id");
    } else if (req.method === "POST") {
      const body = await req.json();
      patientId = body.patient_id || body.filters?.patient_id;
    }

    // Buscar agendamentos do Supabase externo (fechado)
    const ext = await externalRest(
      "/rest/v1/appointments",
      "GET",
      undefined,
      patientId ? { patient_id: `eq.${patientId}` } : undefined
    );

    if (ext.status >= 400) {
      return errorResponse("Failed to fetch external appointments");
    }

    // Buscar notificações pendentes do nosso DB
    const { data: notifications } = await mydb
      .from("notifications_queue")
      .select("*")
      .eq("status", "pending");

    // Mesclar dados
    const merged = ext.data.map((a: any) => {
      const meta = notifications?.find(
        (n: any) => n.payload?.appointment_id === a.id
      );
      return { ...a, meta };
    });

    return jsonResponse(merged);
  } catch (error: any) {
    console.error("Error in appointments function:", error);
    return errorResponse(error?.message || "Unknown error");
  }
});
