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, hasPermission } from "../../lib/auth.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", { headers: corsHeaders() });
  }

  try {
    const auth = await validateAuth(req);
    if (!auth) {
      return errorResponse("Não autorizado", 401);
    }

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

    if (req.method !== "GET") {
      return errorResponse("Method not allowed", 405);
    }

    // Apenas médico ou staff pode ver sua fila
    if (
      auth.userId !== doctorId &&
      !hasPermission(auth.role, ["admin", "secretary"])
    ) {
      return errorResponse("Sem permissão", 403);
    }

    // Buscar fila virtual
    const queueRes = await mydb
      .from("virtual_queue")
      .select("*")
      .eq("status", "waiting")
      .order("position", { ascending: true });

    if (queueRes.error) {
      return errorResponse(queueRes.error.message);
    }

    // Audit log
    await mydb.from("audit_log").insert({
      user_id: auth.userId,
      action: "view_virtual_queue",
      target_type: "virtual_queue",
      payload: { doctor_id: doctorId, count: queueRes.data?.length || 0 },
    });

    return jsonResponse({
      queue: queueRes.data || [],
    });
  } catch (error: unknown) {
    console.error("[virtual-queue]", error);
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
