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

/**
 * POST /virtual-queue/advance
 * Avançar próximo paciente na fila (chamar próximo)
 *
 * Body:
 * {
 *   doctor_id: uuid,
 *   completed: boolean,
 *   duration_minutes?: number,
 *   notes?: string
 * }
 *
 * Returns:
 * {
 *   success: boolean,
 *   called_patient_id: uuid,
 *   next_position?: number
 * }
 */

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

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

    if (req.method !== "POST") {
      return errorResponse("Method not allowed", 405);
    }

    const body = await req.json();
    const { doctor_id, completed, duration_minutes, notes } = body;

    // Apenas médico ou staff pode chamar próximo
    if (
      auth.userId !== doctor_id &&
      !hasPermission(auth.role, ["admin", "secretary"])
    ) {
      return errorResponse("Sem permissão", 403);
    }

    // Obter próximo paciente na fila
    const currentRes = await mydb
      .from("virtual_queue")
      .select("*")
      .eq("status", "waiting")
      .order("position", { ascending: true })
      .limit(1)
      .single();

    if (currentRes.error || !currentRes.data) {
      return errorResponse("Nenhum paciente na fila", 404);
    }

    const current = currentRes.data;

    // Atualizar status do paciente atual
    await mydb
      .from("virtual_queue")
      .update({
        status: completed ? "completed" : "called",
        called_at: new Date().toISOString(),
      })
      .eq("id", current.id);

    // Obter próximo paciente
    const nextRes = await mydb
      .from("virtual_queue")
      .select("*")
      .eq("status", "waiting")
      .order("position", { ascending: true })
      .limit(1);

    let nextPatient = null;
    if (nextRes.data && nextRes.data.length > 0) {
      nextPatient = nextRes.data[0];
    }

    // Audit log
    await mydb.from("audit_log").insert({
      user_id: auth.userId,
      action: "advance_virtual_queue",
      target_type: "virtual_queue",
      payload: {
        called_patient: current.patient_id,
        next_patient: nextPatient?.patient_id,
        completed,
        duration_minutes,
        notes,
      },
    });

    return jsonResponse({
      success: true,
      called_patient_id: current.patient_id,
      next_position: nextPatient?.position,
    });
  } catch (error: unknown) {
    console.error("[advance]", error);
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
