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

export async function PUT(
  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 { status } = await request.json();
    const { id } = params;

    const booking = await prisma.booking.update({
      where: { id },
      data: { status },
    });

    // Create notification
    await prisma.notification.create({
      data: {
        type: 'BOOKING_STATUS_CHANGED',
        title: 'Buchungsstatus geändert',
        message: `Buchung ${booking.bookingNumber} → ${status}`,
        metadata: {
          bookingId: booking.id,
          newStatus: status,
        },
      },
    });

    return NextResponse.json({ success: true, booking });
  } catch (error) {
    console.error('Status update error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
