import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session || session.user.role !== 'DRIVER') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const tour = await prisma.tour.findUnique({
      where: { 
        id: params.id,
        driverId: session.user.id,
      },
      include: {
        tourStops: {
          include: {
            booking: {
              include: {
                photobox: {
                  select: {
                    model: true,
                    serialNumber: true,
                  },
                },
              },
            },
            photos: {
              select: {
                id: true,
                photoType: true,
                fileName: true,
              },
            },
          },
          orderBy: {
            stopOrder: 'asc',
          },
        },
      },
    });

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

    return NextResponse.json({ tour });
  } catch (error: any) {
    console.error('Tour fetch error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to fetch tour' },
      { status: 500 }
    );
  }
}
