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);
    }

    const url = new URL(req.url);
    const sessionId = url.pathname.split("/").pop();

    const res = await mydb
      .from("teleconsult_sessions")
      .select("*")
      .eq("id", sessionId)
      .single();

    if (res.error || !res.data) {
      return errorResponse("Sessão não encontrada", 404);
    }

    return jsonResponse({
      session: res.data,
      status: res.data.ended_at ? "ended" : "active",
      duration_minutes: res.data.duration_minutes,
    });
  } catch (error: unknown) {
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
