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

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 bookingId = params.id;

    const booking = await prisma.booking.findUnique({
      where: { id: bookingId },
      include: {
        location: true,
        photobox: true,
      },
    });

    if (!booking) {
      return NextResponse.json({ error: 'Buchung nicht gefunden' }, { status: 404 });
    }

    let priceConfig = null;
    if (booking.photobox?.model && booking.locationId) {
      priceConfig = await prisma.priceConfig.findUnique({
        where: {
          locationId_model: {
            locationId: booking.locationId,
            model: booking.photobox.model,
          },
        },
      });
    }

    const bookingWithPriceConfig = {
      ...booking,
      priceConfig,
    };

    const signatureData = booking.contractSignedOnline ? booking.contractSignatureData ?? undefined : undefined;

    const pdfBuffer = await generateContractFromTemplate(
      bookingWithPriceConfig,
      booking.location,
      booking.photobox,
      signatureData
    );

    return new NextResponse(new Uint8Array(pdfBuffer), {
      status: 200,
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename="Mietvertrag_${booking.bookingNumber}.pdf"`,
      },
    });

  } catch (error: any) {
    console.error('❌ Contract-PDF-Download Fehler:', error);
    return NextResponse.json(
      { error: error.message || 'PDF-Download fehlgeschlagen' },
      { status: 500 }
    );
  }
}
