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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const photoId = parseInt(id, 10);
    
    if (isNaN(photoId)) {
      return NextResponse.json(
        { error: 'Invalid photo ID' },
        { status: 400 }
      );
    }

    // Get the current photo to find its date_taken for ordering
    const currentPhoto = await prisma.photo.findUnique({
      where: { id: photoId },
      select: { date_taken: true },
    });

    if (!currentPhoto) {
      return NextResponse.json(
        { error: 'Photo not found' },
        { status: 404 }
      );
    }

    // Get previous photo (earlier date_taken, or same date_taken with higher ID)
    const previousPhoto = await prisma.photo.findFirst({
      where: {
        processed: true,
        OR: [
          {
            date_taken: {
              lt: currentPhoto.date_taken || new Date(),
            },
          },
          {
            date_taken: currentPhoto.date_taken,
            id: {
              gt: photoId,
            },
          },
        ],
      },
      orderBy: [
        { date_taken: 'desc' },
        { id: 'asc' },
      ],
      select: { id: true },
    });

    // Get next photo (later date_taken, or same date_taken with lower ID)
    const nextPhoto = await prisma.photo.findFirst({
      where: {
        processed: true,
        OR: [
          {
            date_taken: {
              gt: currentPhoto.date_taken || new Date(),
            },
          },
          {
            date_taken: currentPhoto.date_taken,
            id: {
              lt: photoId,
            },
          },
        ],
      },
      orderBy: [
        { date_taken: 'asc' },
        { id: 'desc' },
      ],
      select: { id: true },
    });

    return NextResponse.json({
      previous: previousPhoto?.id || null,
      next: nextPhoto?.id || null,
    });
  } catch (error) {
    console.error('Error fetching adjacent photos:', error);
    return NextResponse.json(
      { error: 'Failed to fetch adjacent photos' },
      { status: 500 }
    );
  }
}

