import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth-utils";
import prisma from "@/lib/db";
import { sendBookingConfirmationEmail } from "@/lib/email";

/**
 * PATCH /api/bookings/[id]
 * Update booking status (confirm or reject)
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const user = await getCurrentUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await params;
    const body = await request.json();
    const { status } = body;

    if (!status || !["CONFIRMED", "REJECTED"].includes(status)) {
      return NextResponse.json(
        { error: "Invalid status. Must be CONFIRMED or REJECTED" },
        { status: 400 }
      );
    }

    // Get the booking with tour and user details
    const booking = await prisma.booking.findUnique({
      where: { id },
      include: {
        tour: {
          select: {
            id: true,
            title: true,
            slug: true,
            meetingPoint: true,
            priceCents: true,
            createdById: true,
            createdBy: {
              select: {
                name: true,
                email: true,
              },
            },
            hosts: {
              select: {
                userId: true,
                accepted: true,
              },
            },
          },
        },
        user: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
      },
    });

    if (!booking) {
      return NextResponse.json({ error: "Booking not found" }, { status: 404 });
    }

    // Check if user is the guide or a co-host
    const isGuide = booking.tour.createdById === user.id;
    const isCoHost = booking.tour.hosts.some(
      (host) => host.userId === user.id && host.accepted
    );

    if (!isGuide && !isCoHost) {
      return NextResponse.json(
        { error: "You are not authorized to update this booking" },
        { status: 403 }
      );
    }

    // Check if booking is already confirmed or rejected
    if (booking.status !== "PENDING") {
      return NextResponse.json(
        { error: `Booking is already ${booking.status.toLowerCase()}` },
        { status: 400 }
      );
    }

    // Update booking status
    const updatedBooking = await prisma.booking.update({
      where: { id },
      data: { status },
    });

    // Send confirmation email if booking was confirmed
    if (status === "CONFIRMED") {
      await sendBookingConfirmationEmail({
        explorerName: booking.user.name || "Explorer",
        explorerEmail: booking.user.email,
        tourTitle: booking.tour.title,
        tourSlug: booking.tour.slug,
        bookingDate: booking.date.toLocaleDateString("en-US", {
          weekday: "long",
          year: "numeric",
          month: "long",
          day: "numeric",
        }),
        numberOfGuests: booking.numberOfGuests,
        totalPrice: `CHF ${(booking.totalPrice / 100).toFixed(2)}`,
        guideName: booking.tour.createdBy.name || "Your guide",
        guideEmail: booking.tour.createdBy.email,
      });
    }

    return NextResponse.json({
      booking: updatedBooking,
      message: `Booking ${status.toLowerCase()} successfully`,
    });
  } catch (error) {
    console.error("Error updating booking:", error);
    return NextResponse.json(
      { error: "Failed to update booking" },
      { status: 500 }
    );
  }
}
