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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  try {
    const { slug } = await params;

    const tour = await prisma.tour.findUnique({
      where: { 
        slug,
        published: true,
        archived: false,
      },
      include: {
        createdBy: {
          select: {
            id: true,
            name: true,
            bio: true,
            image: true,
          },
        },
        images: {
          orderBy: { order: "asc" },
        },
        reviews: {
          include: {
            user: {
              select: {
                name: true,
                image: true,
              },
            },
          },
          orderBy: { createdAt: "desc" },
        },
        hosts: {
          where: {
            accepted: true,
          },
          include: {
            user: {
              select: {
                id: true,
                name: true,
                image: true,
              },
            },
          },
        },
        _count: {
          select: {
            bookings: true,
            reviews: true,
          },
        },
      },
    });

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

    // Format response
    const formattedTour = {
      id: tour.id,
      title: tour.title,
      slug: tour.slug,
      description: tour.description,
      city: tour.city,
      meetingPoint: tour.meetingPoint,
      meetingPointLat: tour.meetingPointLat,
      meetingPointLng: tour.meetingPointLng,
      durationMin: tour.durationMin,
      priceCents: tour.priceCents,
      maxGuests: tour.maxGuests,
      included: tour.included,
      tags: tour.tags,
      avgRating: tour.avgRating,
      reviewCount: tour._count.reviews,
      bookingCount: tour._count.bookings,
      published: tour.published,
      createdAt: tour.createdAt,
      images: tour.images.map((img) => ({
        id: img.id,
        url: img.url,
        order: img.order,
      })),
      guide: {
        id: tour.createdBy.id,
        name: tour.createdBy.name,
        bio: tour.createdBy.bio,
        image: tour.createdBy.image,
      },
      coHosts: tour.hosts.map((host) => ({
        id: host.user.id,
        name: host.user.name,
        image: host.user.image,
      })),
      reviews: tour.reviews.map((review) => ({
        id: review.id,
        rating: review.rating,
        comment: review.comment,
        createdAt: review.createdAt,
        user: {
          name: review.user.name,
          image: review.user.image,
        },
      })),
    };

    return NextResponse.json({ tour: formattedTour });
  } catch (error) {
    console.error("Error fetching tour:", error);
    return NextResponse.json(
      { error: "Failed to fetch tour" },
      { status: 500 }
    );
  }
}
