import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { routeService } from '@/lib/route-optimization';

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

    const tour = await prisma.tour.findUnique({
      where: { id: params.id },
      include: {
        bookings: {
          include: {
            location: true,
          },
          orderBy: {
            setupTimeStart: 'asc',
          },
        },
        driver: true,
      },
    });

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

    if (tour.bookings.length === 0) {
      return NextResponse.json({ error: 'Keine Buchungen in dieser Tour' }, { status: 400 });
    }

    const stops = tour.bookings.map((booking) => ({
      address: `${booking.eventAddress}, ${booking.eventZip} ${booking.eventCity}`,
      bookingId: booking.id,
      setupTime: booking.setupTimeStart.toISOString(),
    }));

    const startLocation = tour.bookings[0].location.city;

    const optimizedRoute = await routeService.optimizeRouteWithTimeWindows(
      stops,
      startLocation
    );

    if (!optimizedRoute) {
      return NextResponse.json(
        { error: 'Routenoptimierung fehlgeschlagen' },
        { status: 500 }
      );
    }

    const updatedTour = await prisma.tour.update({
      where: { id: params.id },
      data: {
        routeOptimized: optimizedRoute as any,
        totalDistance: optimizedRoute.totalDistance,
        estimatedDuration: optimizedRoute.totalDuration,
      },
      include: {
        bookings: {
          include: {
            location: true,
          },
        },
        driver: true,
      },
    });

    return NextResponse.json({
      success: true,
      tour: updatedTour,
      route: optimizedRoute,
    });
  } catch (error) {
    console.error('Route optimization error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
