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 } from "../../lib/auth.ts";

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 { appointment_id, room_provider, participants } = body;

    const res = await mydb
      .from("teleconsult_sessions")
      .insert({
        appointment_id,
        provider: room_provider || "jitsi",
        room_id: `room_${Date.now()}`,
        room_url: `https://jitsi.mediconnect.local/${Date.now()}`,
        participants,
        started_at: new Date().toISOString(),
      })
      .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);
  }
});
