import { NextResponse } from "next/server"
import { createClient } from "@/lib/supabase/server"
import { isAdminUser } from "@/lib/auth/is-admin"

type ReconfirmBody = {
  action?: "confirm"
}

export async function POST(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params
  const reservationId = id?.trim()

  if (!reservationId) {
    return NextResponse.json({ error: "El id de la reserva es obligatorio" }, { status: 400 })
  }

  const body = (await request.json().catch(() => ({}))) as ReconfirmBody
  if (body.action && body.action !== "confirm") {
    return NextResponse.json({ error: "Acción de reconfirmación no soportada" }, { status: 400 })
  }

  const supabase = await createClient()
  const {
    data: { user },
    error: userError,
  } = await supabase.auth.getUser()

  if (userError || !user) {
    return NextResponse.json({ error: "No autorizado" }, { status: 401 })
  }

  const { data: reservation, error: reservationError } = await supabase
    .from("reservations")
    .select("id, user_id, status")
    .eq("id", reservationId)
    .maybeSingle()

  if (reservationError) {
    return NextResponse.json({ error: "No se pudo consultar la reserva" }, { status: 500 })
  }
  if (!reservation) {
    return NextResponse.json({ error: "Reserva no encontrada" }, { status: 404 })
  }
  if (reservation.status !== "confirmed") {
    return NextResponse.json({ error: "Solo se pueden reconfirmar reservas confirmadas" }, { status: 409 })
  }

  const canManage = reservation.user_id === user.id || isAdminUser(user)
  if (!canManage) {
    return NextResponse.json({ error: "No tienes permisos para reconfirmar esta reserva" }, { status: 403 })
  }

  const { data: updated, error: updateError } = await (supabase.from("reservations") as any)
    .update({
      reconfirmation_status: "confirmed",
      reconfirmed_at: new Date().toISOString(),
    })
    .eq("id", reservation.id)
    .eq("status", "confirmed")
    .select("id, status, reconfirmation_status, reconfirmed_at")
    .maybeSingle()

  if (updateError) {
    return NextResponse.json({ error: "No se pudo reconfirmar la reserva" }, { status: 500 })
  }
  if (!updated) {
    return NextResponse.json({ error: "No se pudo reconfirmar la reserva" }, { status: 409 })
  }

  return NextResponse.json({ ok: true, reservation: updated })
}
