import { notFound, redirect } from "next/navigation";
import { Suspense } from "react";
import prisma from "@/lib/db";
import { getCurrentUser } from "@/lib/auth-utils";
import { getImageDisplayUrl } from "@/lib/image-utils";
import { TourDetailClient } from "./tour-detail-client";

interface TourPageProps {
  params: Promise<{ slug: string }>;
}

// Generate static params for top tours at build time
export async function generateStaticParams() {
  try {
    const tours = await prisma.tour.findMany({
      where: { 
        published: true, 
        archived: false 
      },
      select: { slug: true },
      take: 50, // Pre-generate top 50 tours
      orderBy: [
        { avgRating: 'desc' },
        { reviewCount: 'desc' },
      ],
    });

    return tours.map((tour) => ({
      slug: tour.slug,
    }));
  } catch (error) {
    console.error('Error generating static params:', error);
    return [];
  }
}

// Revalidate every hour
export const revalidate = 3600;

export default async function TourPage({ params }: TourPageProps) {
  const { slug } = await params;
  const user = await getCurrentUser();

  // Optimized query with explicit select to fetch only needed fields
  const tour = await prisma.tour.findUnique({
    where: { slug },
    select: {
      id: true,
      title: true,
      slug: true,
      description: true,
      city: true,
      meetingPoint: true,
      meetingPointLat: true,
      meetingPointLng: true,
      priceCents: true,
      durationMin: true,
      maxGuests: true,
      avgRating: true,
      reviewCount: true,
      tags: true,
      included: true,
      createdById: true,
      createdBy: {
        select: {
          id: true,
          name: true,
          email: true,
          image: true,
          bio: true,
        },
      },
      images: {
        select: {
          url: true,
          order: true,
        },
        orderBy: { order: "asc" },
      },
      reviews: {
        select: {
          id: true,
          rating: true,
          comment: true,
          createdAt: true,
          user: {
            select: {
              name: true,
              image: true,
            },
          },
        },
        orderBy: { createdAt: "desc" },
        take: 10,
      },
      hosts: {
        where: {
          accepted: true,
        },
        select: {
          user: {
            select: {
              id: true,
              name: true,
              image: true,
            },
          },
        },
      },
      _count: {
        select: {
          bookings: true,
          reviews: true,
        },
      },
    },
  });

  if (!tour) {
    notFound();
  }

  // If user is the tour author (guide), redirect to preview page
  if (user && tour.createdById === user.id) {
    redirect(`/tours/preview/${tour.id}`);
  }

  // Process image URLs to get signed URLs for S3 images
  const processedImages = await Promise.all(
    (tour.images || []).map(async (image) => ({
      ...image,
      displayUrl: await getImageDisplayUrl(image.url),
    }))
  );

  // Create tour data with processed images
  const tourWithDisplayUrls = {
    ...tour,
    images: processedImages,
  };

  return (
    <Suspense fallback={<div className="container mx-auto px-4 py-8">Loading...</div>}>
      <TourDetailClient tour={tourWithDisplayUrls} user={user} />
    </Suspense>
  );
}
