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

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 body = await request.json();
    const { id } = params;

    const booking = await prisma.booking.update({
      where: { id },
      data: {
        customerName: body.customerName,
        customerEmail: body.customerEmail,
        customerPhone: body.customerPhone,
        customerAddress: body.customerAddress,
        customerCity: body.customerCity,
        customerZip: body.customerZip,
        notes: body.notes,
        internalNotes: body.internalNotes,
      },
      include: {
        location: true,
        photobox: true,
      },
    });

    try {
      await nextcloudCalendar.syncBookingToCalendar(booking);
    } catch (calError) {
      console.error('Calendar sync error after booking update:', calError);
    }

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

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

    if (!status) {
      return NextResponse.json({ error: 'Status is required' }, { status: 400 });
    }

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

    try {
      if (status === 'CANCELLED') {
        await nextcloudCalendar.removeBookingFromCalendar(booking.id);
      } else {
        await nextcloudCalendar.syncBookingToCalendar(booking);
      }
    } catch (calError) {
      console.error('Calendar sync error after status change:', calError);
    }

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