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

export async function POST(request: NextRequest) {
  try {
    const user = await getCurrentUser();

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

    const body = await request.json();
    const { tourId, date, numberOfGuests, notes } = body;

    if (!tourId || !date || !numberOfGuests) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 }
      );
    }

    // Validate numberOfGuests
    if (numberOfGuests < 1 || !Number.isInteger(numberOfGuests)) {
      return NextResponse.json(
        { error: "Number of guests must be at least 1" },
        { status: 400 }
      );
    }

    // Get the tour with guide info
    const tour = await prisma.tour.findUnique({
      where: { id: tourId },
      select: {
        id: true,
        title: true,
        slug: true,
        priceCents: true,
        maxGuests: true,
        published: true,
        archived: true,
        createdById: true,
        createdBy: {
          select: {
            id: true,
            name: true,
            email: true,
          },
        },
      },
    });

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

    // Check if tour is published
    if (!tour.published) {
      return NextResponse.json(
        { error: "This tour is not available for booking" },
        { status: 400 }
      );
    }

    // Check if tour is archived
    if (tour.archived) {
      return NextResponse.json(
        { error: "This tour has been archived" },
        { status: 400 }
      );
    }

    // Prevent guide from booking their own tour
    if (tour.createdById === user.id) {
      return NextResponse.json(
        { error: "You cannot book your own tour" },
        { status: 400 }
      );
    }

    // Validate date is in the future
    const bookingDate = new Date(date);
    const now = new Date();
    if (bookingDate <= now) {
      return NextResponse.json(
        { error: "Booking date must be in the future" },
        { status: 400 }
      );
    }

    // Validate number of guests
    if (tour.maxGuests && numberOfGuests > tour.maxGuests) {
      return NextResponse.json(
        { error: `Maximum ${tour.maxGuests} guests allowed` },
        { status: 400 }
      );
    }

    // Check if user already has a pending or confirmed booking for this tour on the SAME DATE
    // Users can book the same tour multiple times for different dates
    const existingBooking = await prisma.booking.findFirst({
      where: {
        userId: user.id,
        tourId,
        date: bookingDate,
        status: {
          in: ["PENDING", "CONFIRMED"],
        },
      },
    });

    if (existingBooking) {
      return NextResponse.json(
        {
          error:
            "You already have a booking for this tour on the selected date",
        },
        { status: 400 }
      );
    }

    // Calculate total price
    const totalPrice = tour.priceCents
      ? tour.priceCents * numberOfGuests
      : 0;

    // Create the booking
    const booking = await prisma.booking.create({
      data: {
        tourId,
        userId: user.id,
        date: bookingDate,
        numberOfGuests,
        totalPrice,
        notes: notes || null,
        status: "PENDING",
      },
    });

    // Send email notification to guide
    await sendBookingRequestEmail({
      guideName: tour.createdBy.name || "Guide",
      guideEmail: tour.createdBy.email,
      explorerName: user.name || "Explorer",
      tourTitle: tour.title,
      bookingDate: bookingDate.toLocaleDateString("en-US", {
        weekday: "long",
        year: "numeric",
        month: "long",
        day: "numeric",
      }),
      numberOfGuests,
      totalPrice: `CHF ${(totalPrice / 100).toFixed(2)}`,
    });

    return NextResponse.json(
      {
        booking,
        message: "Booking request sent successfully",
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("Booking creation error:", error);
    return NextResponse.json(
      { error: "Failed to create booking" },
      { status: 500 }
    );
  }
}

export async function GET() {
  try {
    const user = await getCurrentUser();

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

    // Get bookings where user is either the explorer or the guide
    const bookings = await prisma.booking.findMany({
      where: {
        OR: [
          { userId: user.id }, // User is the explorer
          {
            tour: {
              OR: [
                { createdById: user.id }, // User is the guide
                {
                  hosts: {
                    some: {
                      userId: user.id,
                      accepted: true, // User is a co-host
                    },
                  },
                },
              ],
            },
          },
        ],
      },
      include: {
        tour: {
          select: {
            id: true,
            title: true,
            slug: true,
            city: true,
            meetingPoint: true,
            durationMin: true,
            priceCents: true,
            images: {
              select: {
                url: true,
              },
              take: 1,
            },
            createdBy: {
              select: {
                id: true,
                name: true,
                email: true,
                image: true,
              },
            },
          },
        },
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            image: true,
          },
        },
      },
      orderBy: { createdAt: "desc" },
    });

    return NextResponse.json({ bookings });
  } catch (error) {
    console.error("Fetch bookings error:", error);
    return NextResponse.json(
      { error: "Failed to fetch bookings" },
      { status: 500 }
    );
  }
}
