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

export async function POST(
  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,
      },
    });

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

    if (booking.lexofficeOfferId) {
      return NextResponse.json(
        { error: 'Quotation already exists', offerId: booking.lexofficeOfferId },
        { status: 400 }
      );
    }

    const lexoffice = new LexOfficeService();

    // 1. Create or get contact
    let contactId = booking.lexofficeContactId;
    if (!contactId) {
      contactId = await lexoffice.createContactFromBooking(booking);
      
      await prisma.booking.update({
        where: { id: booking.id },
        data: { lexofficeContactId: contactId },
      });
    }

    // 2. Create quotation
    const quotationId = await lexoffice.createQuotationFromBooking(booking, contactId);

    // 3. Update booking with offer ID
    await prisma.booking.update({
      where: { id: booking.id },
      data: { lexofficeOfferId: quotationId },
    });

    return NextResponse.json({
      success: true,
      quotation: {
        id: quotationId,
      },
      contactId,
    });
  } catch (error: any) {
    console.error('LexOffice quotation creation error:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to create quotation' },
      { status: 500 }
    );
  }
}
