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

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 booking = await prisma.booking.findUnique({
      where: { id: params.id },
    });

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

    if (booking.status !== 'READY_FOR_ASSIGNMENT') {
      return NextResponse.json({ error: 'Buchung muss im Status READY_FOR_ASSIGNMENT sein' }, { status: 400 });
    }

    await prisma.booking.update({
      where: { id: params.id },
      data: {
        status: 'OPEN_FOR_DRIVERS',
        openForDrivers: true,
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Release to drivers error:', error);
    return NextResponse.json(
      { error: 'Freigabe fehlgeschlagen' },
      { status: 500 }
    );
  }
}
