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

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

    const tour = await prisma.tour.findUnique({
      where: { id: params.id },
      include: {
        driver: {
          select: {
            id: true,
            name: true,
            email: true,
            phoneNumber: true,
            vehiclePlate: true,
            vehicleModel: true,
          },
        },
        bookings: {
          include: {
            location: {
              select: {
                name: true,
                city: true,
              },
            },
            photobox: {
              select: {
                model: true,
                serialNumber: true,
              },
            },
          },
          orderBy: {
            setupTimeStart: 'asc',
          },
        },
      },
    });

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

    if (session.user.role !== 'ADMIN' && session.user.id !== tour.driverId) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    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 }
    );
  }
}

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

    const body = await request.json();
    const { driverId, status, notes, bookingIds } = body;

    const updateData: any = {};
    if (driverId !== undefined) updateData.driverId = driverId;
    if (status !== undefined) {
      updateData.status = status;
      if (status === 'IN_PROGRESS' && !updateData.startedAt) {
        updateData.startedAt = new Date();
      }
      if (status === 'COMPLETED' && !updateData.completedAt) {
        updateData.completedAt = new Date();
      }
    }
    if (notes !== undefined) updateData.notes = notes;

    if (bookingIds !== undefined) {
      await prisma.booking.updateMany({
        where: { tourId: params.id },
        data: { tourId: null },
      });

      if (bookingIds.length > 0) {
        await prisma.booking.updateMany({
          where: { id: { in: bookingIds } },
          data: { tourId: params.id },
        });

        const bookings = await prisma.booking.findMany({
          where: { id: { in: bookingIds } },
          select: {
            eventAddress: true,
            eventCity: true,
            eventZip: true,
            setupTimeStart: true,
          },
        });

        try {
          const routeData = await optimizeRoute(bookings);
          updateData.routeOptimized = routeData;
          updateData.totalDistance = routeData.totalDistance;
          updateData.estimatedDuration = routeData.totalDuration;
        } catch (routeError) {
          console.error('Route optimization error:', routeError);
        }
      }
    }

    const tour = await prisma.tour.update({
      where: { id: params.id },
      data: updateData,
      include: {
        driver: true,
        bookings: true,
      },
    });

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

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

    await prisma.booking.updateMany({
      where: { tourId: params.id },
      data: { tourId: null },
    });

    await prisma.tour.delete({
      where: { id: params.id },
    });

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