import { notFound } from 'next/navigation';
import { PhotoViewerClient } from '@/components/PhotoViewerClient';
import { prisma } from '@/lib/db';
import { serializePhoto, serializePhotos } from '@/lib/serialize';

// Force dynamic rendering to prevent database queries during build
export const dynamic = 'force-dynamic';

async function getPhoto(id: number) {
  try {
    const photo = await prisma.photo.findUnique({
      where: { id },
      include: {
        Face: {
          include: {
            Person: true,
          },
        },
        PhotoTagLinkage: {
          include: {
            Tag: true,
          },
        },
      },
    });

    return photo ? serializePhoto(photo) : null;
  } catch (error) {
    console.error('Error fetching photo:', error);
    return null;
  }
}

async function getPhotosByIds(ids: number[]) {
  try {
    const photos = await prisma.photo.findMany({
      where: {
        id: { in: ids },
        processed: true,
      },
      include: {
        Face: {
          include: {
            Person: true,
          },
        },
        PhotoTagLinkage: {
          include: {
            Tag: true,
          },
        },
      },
      orderBy: { date_taken: 'desc' },
    });

    return serializePhotos(photos);
  } catch (error) {
    console.error('Error fetching photos:', error);
    return [];
  }
}

export default async function PhotoPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ photos?: string; index?: string }>;
}) {
  const { id } = await params;
  const { photos: photosParam, index: indexParam } = await searchParams;
  const photoId = parseInt(id, 10);

  if (isNaN(photoId)) {
    notFound();
  }

  // Get the current photo
  const photo = await getPhoto(photoId);
  if (!photo) {
    notFound();
  }

  // If we have a photo list context, fetch all photos for client-side navigation
  let allPhotos: typeof photo[] = [];
  let currentIndex = 0;

  if (photosParam && indexParam) {
    const photoIds = photosParam.split(',').map(Number).filter(Boolean);
    const parsedIndex = parseInt(indexParam, 10);
    
    if (photoIds.length > 0 && !isNaN(parsedIndex)) {
      allPhotos = await getPhotosByIds(photoIds);
      // Maintain the original order from the photoIds array
      const photoMap = new Map(allPhotos.map((p) => [p.id, p]));
      allPhotos = photoIds.map((id) => photoMap.get(id)).filter(Boolean) as typeof photo[];
      currentIndex = parsedIndex;
    }
  }

  return (
    <PhotoViewerClient
      initialPhoto={photo}
      allPhotos={allPhotos}
      currentIndex={currentIndex}
    />
  );
}

