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

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,
        bookingEquipment: {
          include: {
            equipment: 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 lineItems: any[] = [];
    const withPrintFlat = booking.withPrintFlat !== false;

    // Photobox LineItem
    const photoboxArticleId = withPrintFlat 
      ? (priceConfig?.lexofficeArticleIdWithFlat || priceConfig?.lexofficeArticleId)
      : priceConfig?.lexofficeArticleId;

    const boxName = booking.photobox?.model || 'Fotobox';
    const flatSuffix = withPrintFlat ? ' mit Druckflatrate' : ' (nur digital)';

    const photoboxItem: any = {
      type: (photoboxArticleId && photoboxArticleId.trim()) ? 'material' : 'custom',
      quantity: 1,
      unitName: 'Stück',
      name: `${boxName}${flatSuffix}`,
    };

    if (photoboxArticleId && photoboxArticleId.trim()) {
      photoboxItem.id = photoboxArticleId;
    } else {
      photoboxItem.description = `Event am ${new Date(booking.eventDate).toLocaleDateString('de-DE')} in ${booking.eventCity}`;
      photoboxItem.unitPrice = {
        currency: 'EUR',
        netAmount: priceConfig?.basePrice || 1,
        taxRatePercentage: 19,
      };
    }

    lineItems.push(photoboxItem);

    return NextResponse.json({
      booking: {
        id: booking.id,
        bookingNumber: booking.bookingNumber,
        locationId: booking.locationId,
        photoboxModel: booking.photobox?.model,
        withPrintFlat: booking.withPrintFlat,
        distance: booking.distance,
      },
      priceConfig: priceConfig ? {
        id: priceConfig.id,
        basePrice: priceConfig.basePrice,
        kmFlatRate: priceConfig.kmFlatRate,
        kmFlatRateUpTo: priceConfig.kmFlatRateUpTo,
        pricePerKm: priceConfig.pricePerKm,
        kmMultiplier: priceConfig.kmMultiplier,
        lexofficeArticleId: priceConfig.lexofficeArticleId,
        lexofficeArticleIdWithFlat: priceConfig.lexofficeArticleIdWithFlat,
        lexofficeKmFlatArticleId: priceConfig.lexofficeKmFlatArticleId,
        lexofficeKmExtraArticleId: priceConfig.lexofficeKmExtraArticleId,
      } : null,
      lineItems,
      photoboxArticleId,
    });

  } catch (error: any) {
    console.error('❌ Debug Fehler:', error);
    return NextResponse.json(
      { error: error.message, stack: error.stack },
      { status: 500 }
    );
  }
}
