2025-12-06 19:13:27 -03:00

86 lines
2.1 KiB
TypeScript

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";
/**
* 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", { status: 200, headers: corsHeaders() });
}
try {
if (req.method !== "POST") {
return errorResponse("Method not allowed", 405);
}
const body = await req.json();
const { doctor_id, completed, duration_minutes, notes } = body;
// 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];
}
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);
}
});