import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
import { mydb } from "../../lib/mySupabase.ts";
import { corsHeaders, jsonResponse, errorResponse } from "../../lib/utils.ts";
import { validateAuth, hasPermission } from "../../lib/auth.ts";
import {
  createWaitlistSchema,
  waitlistFiltersSchema,
} 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);
    }

    // POST com method GET no body (padrão Supabase callFunction)
    if (req.method === "POST") {
      const body = await req.json();

      // Se é um GET simulado via POST
      if (body.method === "GET") {
        const { patient_id, doctor_id, status } = body.filters || {};

        let query = mydb.from("waitlist").select("*");

        if (patient_id) query = query.eq("patient_id", patient_id);
        if (doctor_id) query = query.eq("doctor_id", doctor_id);
        if (status) query = query.eq("status", status);

        const { data, error } = await query;

        if (error) {
          return errorResponse(error.message);
        }

        return jsonResponse(data);
      }

      // POST normal - criar entrada na waitlist
      const validatedData = createWaitlistSchema.parse(body);

      // Verificar se é o próprio paciente ou um admin/secretária
      if (
        validatedData.patient_id !== auth.userId &&
        !hasPermission(auth.role, ["admin", "secretary"])
      ) {
        return errorResponse(
          "Sem permissão para adicionar outro paciente",
          403
        );
      }

      const { data, error } = await mydb
        .from("waitlist")
        .insert([validatedData])
        .select();

      // Audit log
      await mydb.from("audit_log").insert({
        user_id: auth.userId,
        action: "create_waitlist",
        target_type: "waitlist",
        target_id: data?.[0]?.id,
        payload: validatedData,
      });

      if (error) {
        return errorResponse(error.message);
      }

      return jsonResponse(data[0]);
    }

    if (req.method === "GET") {
      const url = new URL(req.url);
      const patientId = url.searchParams.get("patient_id");
      const doctorId = url.searchParams.get("doctor_id");

      let query = mydb.from("waitlist").select("*");

      if (patientId) query = query.eq("patient_id", patientId);
      if (doctorId) query = query.eq("doctor_id", doctorId);

      const { data, error } = await query;

      if (error) {
        return errorResponse(error.message);
      }

      return jsonResponse(data);
    }

    return errorResponse("Method not allowed", 405);
  } catch (error) {
    console.error("Error in waitlist function:", error);
    return errorResponse(error.message);
  }
});
