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

104 lines
2.7 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";
/**
* GET /virtual-queue/:doctor_id
* Listar fila virtual do médico
*
* Params:
* doctor_id: uuid
*
* Returns:
* {
* queue: [{
* id: uuid,
* patient_id: uuid,
* position: number,
* status: string,
* estimated_wait_minutes: number,
* checked_in_at: timestamptz
* }]
* }
*/
serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { status: 200, headers: corsHeaders() });
}
try {
const authHeader = req.headers.get("Authorization") || "";
const url = new URL(req.url);
const doctorId = url.pathname.split("/").pop();
if (req.method !== "GET") {
return errorResponse("Method not allowed", 405);
}
if (!doctorId) {
return errorResponse("doctor_id is required", 400);
}
// Buscar fila virtual filtrada por médico
const queueRes = await mydb
.from("virtual_queue")
.select("*")
.eq("external_doctor_id", doctorId)
.eq("status", "waiting")
.order("position", { ascending: true });
if (queueRes.error) {
return errorResponse(queueRes.error.message);
}
// Enriquecer com dados do Supabase externo
const { getExternalPatients } = await import("../_shared/external.ts");
type QueueEntry = {
external_patient_id: string;
[key: string]: unknown;
};
const enrichedQueue = await Promise.all(
(queueRes.data || []).map(async (entry: QueueEntry) => {
try {
const patients = await getExternalPatients(
{ id: entry.external_patient_id },
authHeader
);
const patient = Array.isArray(patients) ? patients[0] : null;
return {
...entry,
patient_name:
(patient as Record<string, unknown>)?.full_name || "Desconhecido",
patient_cpf: (patient as Record<string, unknown>)?.cpf,
};
} catch {
return entry;
}
})
);
// Audit log (simplified - no auth validation)
await mydb.from("audit_log").insert({
action: "view_virtual_queue",
entity_type: "virtual_queue",
external_entity_id: doctorId,
metadata: { doctor_id: doctorId, count: queueRes.data?.length || 0 },
});
return jsonResponse({
queue: enrichedQueue || [],
total_waiting: enrichedQueue.length,
current_patient: enrichedQueue[0] || null,
average_wait_minutes: 15,
});
} catch (error: unknown) {
console.error("[virtual-queue]", error);
const err = error as Error;
return errorResponse(err.message, 500);
}
});