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

function generateTourNumber(): string {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `T${year}${month}${day}-${random}`;
}

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 { driverId } = await request.json();

    if (!driverId) {
      return NextResponse.json({ error: 'Fahrer-ID erforderlich' }, { status: 400 });
    }

    const booking = await prisma.booking.findUnique({
      where: { id: params.id },
    });

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

    if (booking.status !== 'OPEN_FOR_DRIVERS') {
      return NextResponse.json({ error: 'Buchung ist nicht für Zuweisung bereit' }, { status: 400 });
    }

    let tour = await prisma.tour.findFirst({
      where: {
        tourDate: booking.eventDate,
        driverId: driverId,
        status: 'PLANNED',
      },
    });

    if (!tour) {
      tour = await prisma.tour.create({
        data: {
          tourDate: booking.eventDate,
          tourNumber: generateTourNumber(),
          driverId: driverId,
          status: 'PLANNED',
        },
      });
    }

    await prisma.booking.update({
      where: { id: params.id },
      data: {
        tourId: tour.id,
        status: 'ASSIGNED',
      },
    });

    return NextResponse.json({
      success: true,
      tour,
      message: `Buchung wurde Tour ${tour.tourNumber} zugewiesen`,
    });
  } catch (error) {
    console.error('Assign driver error:', error);
    return NextResponse.json(
      { error: 'Zuweisung fehlgeschlagen' },
      { status: 500 }
    );
  }
}
