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) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { available, message } = await request.json();

    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 Fahrer freigegeben' }, { status: 400 });
    }

    const availability = await prisma.driverAvailability.upsert({
      where: {
        bookingId_driverId: {
          bookingId: params.id,
          driverId: session.user.id,
        },
      },
      update: {
        available,
        message,
      },
      create: {
        bookingId: params.id,
        driverId: session.user.id,
        available,
        message,
      },
    });

    return NextResponse.json({ success: true, availability });
  } catch (error) {
    console.error('Availability update error:', error);
    return NextResponse.json(
      { error: 'Verfügbarkeit konnte nicht gespeichert werden' },
      { status: 500 }
    );
  }
}

export async function GET(
  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 availabilities = await prisma.driverAvailability.findMany({
      where: {
        bookingId: params.id,
        available: true,
      },
      include: {
        driver: {
          select: {
            id: true,
            name: true,
            email: true,
            phoneNumber: true,
            vehiclePlate: true,
            vehicleModel: true,
          },
        },
      },
      orderBy: {
        createdAt: 'asc',
      },
    });

    return NextResponse.json({ availabilities });
  } catch (error) {
    console.error('Get availability error:', error);
    return NextResponse.json(
      { error: 'Fehler beim Laden der Verfügbarkeiten' },
      { status: 500 }
    );
  }
}
