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";

/**
 * POST /appointments/checkin
 * Registrar check-in do paciente (chegou no consultório)
 *
 * Body:
 * {
 *   appointment_id: uuid,
 *   check_in_method: 'manual' | 'qr_code' | 'nfc' | 'app' | 'kiosk',
 *   location?: { lat: number, lng: number },
 *   device_info?: { ...metadata }
 * }
 *
 * Returns:
 * {
 *   success: boolean,
 *   appointment_id: uuid,
 *   checked_in_at: timestamptz,
 *   position_in_queue?: number
 * }
 */

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, check_in_method, location, device_info } = body;

    // Registrar check-in no banco
    const checkinRes = await mydb
      .from("checkin_tracking")
      .insert({
        appointment_id,
        patient_id: auth.userId,
        check_in_method,
        location,
        device_info,
      })
      .select();

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

    // Buscar ou criar entrada na virtual_queue
    const queueRes = await mydb
      .from("virtual_queue")
      .select("*")
      .eq("appointment_id", appointment_id)
      .single();

    let position = 1;
    if (!queueRes.data) {
      // Criar entrada na fila
      const newQueueRes = await mydb
        .from("virtual_queue")
        .insert({
          appointment_id,
          patient_id: auth.userId,
          position: 1,
          status: "waiting",
          estimated_wait_minutes: 15,
        })
        .select();

      if (newQueueRes.data) {
        position = newQueueRes.data[0].position;
      }
    } else {
      position = queueRes.data.position;
    }

    // Audit log
    await mydb.from("audit_log").insert({
      user_id: auth.userId,
      action: "checkin_appointment",
      target_type: "appointment",
      target_id: appointment_id,
      payload: { check_in_method, position },
    });

    return jsonResponse({
      success: true,
      appointment_id,
      checked_in_at: new Date().toISOString(),
      position_in_queue: position,
    });
  } catch (error: unknown) {
    console.error("[checkin]", error);
    const err = error as Error;
    return errorResponse(err.message, 500);
  }
});
