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 GET(
  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 booking = await prisma.booking.findUnique({
      where: { id: params.id },
      include: {
        location: true,
        photobox: true,
        bookingEquipment: {
          include: { equipment: true },
        },
      },
    });

    if (!booking) {
      return NextResponse.json({ error: 'Booking not found' }, { status: 404 });
    }

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

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 updateData: any = {};

    if (body.status) updateData.status = body.status;
    if (body.customerName !== undefined) updateData.customerName = body.customerName;
    if (body.customerEmail !== undefined) updateData.customerEmail = body.customerEmail;
    if (body.customerPhone !== undefined) updateData.customerPhone = body.customerPhone;
    if (body.customerAddress !== undefined) updateData.customerAddress = body.customerAddress;
    if (body.customerCity !== undefined) updateData.customerCity = body.customerCity;
    if (body.customerZip !== undefined) updateData.customerZip = body.customerZip;
    if (body.companyName !== undefined) updateData.companyName = body.companyName;
    if (body.invoiceType !== undefined) updateData.invoiceType = body.invoiceType;
    if (body.eventDate !== undefined) updateData.eventDate = new Date(body.eventDate);
    if (body.eventAddress !== undefined) updateData.eventAddress = body.eventAddress;
    if (body.eventCity !== undefined) updateData.eventCity = body.eventCity;
    if (body.eventZip !== undefined) updateData.eventZip = body.eventZip;
    if (body.eventLocation !== undefined) updateData.eventLocation = body.eventLocation;
    if (body.setupTimeStart !== undefined) updateData.setupTimeStart = body.setupTimeStart ? new Date(body.setupTimeStart) : null;
    if (body.setupTimeLatest !== undefined) updateData.setupTimeLatest = body.setupTimeLatest ? new Date(body.setupTimeLatest) : null;
    if (body.dismantleTimeEarliest !== undefined) updateData.dismantleTimeEarliest = body.dismantleTimeEarliest ? new Date(body.dismantleTimeEarliest) : null;
    if (body.dismantleTimeLatest !== undefined) updateData.dismantleTimeLatest = body.dismantleTimeLatest ? new Date(body.dismantleTimeLatest) : null;
    if (body.calculatedPrice !== undefined) updateData.calculatedPrice = body.calculatedPrice;
    if (body.notes !== undefined) updateData.notes = body.notes;
    if (body.withPrintFlat !== undefined) updateData.withPrintFlat = body.withPrintFlat;

    const hasEquipmentUpdate = Array.isArray(body.equipmentIds);
    const hasModelUpdate = body.model !== undefined;

    if (Object.keys(updateData).length === 0 && !hasEquipmentUpdate && !hasModelUpdate) {
      return NextResponse.json({ error: 'Keine Änderungen angegeben' }, { status: 400 });
    }

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

    if (hasModelUpdate && booking.photoboxId) {
      await prisma.photobox.update({
        where: { id: booking.photoboxId },
        data: { model: body.model },
      });
    }

    if (hasEquipmentUpdate) {
      await prisma.bookingEquipment.deleteMany({ where: { bookingId: id } });
      if (body.equipmentIds.length > 0) {
        await prisma.bookingEquipment.createMany({
          data: body.equipmentIds.map((eqId: string) => ({
            bookingId: id,
            equipmentId: eqId,
          })),
        });
      }
    }

    try {
      if (updateData.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 }
    );
  }
}
