import { NextRequest, NextResponse } from "next/server";
import prisma  from "@/lib/db";
import { auth } from "@/lib/auth";
import { sendBookingCompletedEmail } from "@/lib/email";

/**
 * PATCH /api/bookings/[id]/complete
 * Mark a booking as completed (Guide only)
 * - Can only be marked completed by the tour guide
 * - Sends completion email to explorer
 * - Enables reviews for this booking
 */
export async function PATCH(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    // Get user session
    const session = await auth.api.getSession({
      headers: request.headers,
    });

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

    const { id: bookingId } = await context.params;

    // Get the booking with related tour and user info
    const booking = await prisma.booking.findUnique({
      where: { id: bookingId },
      include: {
        tour: {
          include: {
            createdBy: true,
          },
        },
        user: true,
      },
    });

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

    // Verify the user is the guide for this tour
    if (booking.tour.createdBy.id !== session.user.id) {
      return NextResponse.json(
        { error: "Only the tour guide can mark a booking as completed" },
        { status: 403 }
      );
    }

    // Can only complete CONFIRMED bookings
    if (booking.status !== "CONFIRMED") {
      return NextResponse.json(
        { error: `Cannot complete booking with status: ${booking.status}` },
        { status: 400 }
      );
    }

    // Update booking status to COMPLETED
    const updatedBooking = await prisma.booking.update({
      where: { id: bookingId },
      data: {
        status: "COMPLETED",
      },
      include: {
        tour: {
          include: {
            createdBy: true,
          },
        },
        user: true,
      },
    });

    // Send completion email to explorer
    await sendBookingCompletedEmail({
      explorerName: updatedBooking.user.name || "Traveler",
      explorerEmail: updatedBooking.user.email,
      tourTitle: updatedBooking.tour.title,
      guideName: updatedBooking.tour.createdBy.name || "Guide",
      tourDate: updatedBooking.date.toLocaleDateString("en-US", {
        weekday: "long",
        year: "numeric",
        month: "long",
        day: "numeric",
      }),
      tourSlug: updatedBooking.tour.slug,
    });

    return NextResponse.json({
      success: true,
      booking: updatedBooking,
      message: "Booking marked as completed. Tourist can now leave a review!",
    });
  } catch (error) {
    console.error("Error completing booking:", error);
    return NextResponse.json(
      { error: "Failed to complete booking" },
      { status: 500 }
    );
  }
}
