79 lines
2.3 KiB
TypeScript
79 lines
2.3 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";
|
|
|
|
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 {
|
|
appointment_id,
|
|
external_appointment_id,
|
|
room_provider,
|
|
participants,
|
|
} = body;
|
|
|
|
// Usar external_appointment_id como referência
|
|
const targetAppointmentId = external_appointment_id || appointment_id;
|
|
|
|
if (!targetAppointmentId) {
|
|
return errorResponse(
|
|
"appointment_id or external_appointment_id is required",
|
|
400
|
|
);
|
|
}
|
|
|
|
// Buscar dados da consulta do Supabase externo
|
|
const { getExternalAppointments } = await import("../_shared/external.ts");
|
|
const authHeader = req.headers.get("Authorization") || "";
|
|
|
|
let appointmentData = null;
|
|
try {
|
|
const appointments = await getExternalAppointments(
|
|
{
|
|
/* Filtro opcional */
|
|
},
|
|
authHeader
|
|
);
|
|
appointmentData = Array.isArray(appointments)
|
|
? appointments.find((a: any) => a.id === targetAppointmentId)
|
|
: null;
|
|
} catch (e) {
|
|
console.warn("Não foi possível buscar dados da consulta", e);
|
|
}
|
|
|
|
const res = await mydb
|
|
.from("teleconsult_sessions")
|
|
.insert({
|
|
external_appointment_id: targetAppointmentId,
|
|
provider: room_provider || "jitsi",
|
|
room_id: `room_${Date.now()}`,
|
|
room_url: `https://meet.jit.si/mediconnect-${targetAppointmentId}-${Date.now()}`,
|
|
participants: participants || [],
|
|
started_at: new Date().toISOString(),
|
|
metadata: appointmentData
|
|
? {
|
|
doctor_id: appointmentData.doctor_id,
|
|
patient_id: appointmentData.patient_id,
|
|
}
|
|
: null,
|
|
})
|
|
.select();
|
|
|
|
return jsonResponse({
|
|
session_id: res.data?.[0]?.id,
|
|
room_url: res.data?.[0]?.room_url,
|
|
});
|
|
} catch (error: unknown) {
|
|
const err = error as Error;
|
|
return errorResponse(err.message, 500);
|
|
}
|
|
});
|