import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { lexofficeService } from '@/lib/lexoffice';

export async function GET(request: Request) {
  try {
    const authHeader = request.headers.get('authorization');
    if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const bookings = await prisma.booking.findMany({
      where: {
        status: 'CONFIRMED',
        contractSigned: true,
        lexofficeConfirmationId: null,
      },
    });

    let processed = 0;
    const results = [];

    for (const booking of bookings) {
      try {
        let contactId = booking.lexofficeContactId;

        if (!contactId) {
          contactId = await lexofficeService.createContactFromBooking(booking);
          await prisma.booking.update({
            where: { id: booking.id },
            data: { lexofficeContactId: contactId },
          });
        }

        const confirmationId = await lexofficeService.createConfirmationFromBooking(
          booking,
          contactId
        );

        await prisma.booking.update({
          where: { id: booking.id },
          data: {
            status: 'READY_FOR_ASSIGNMENT',
            readyForAssignment: true,
            lexofficeConfirmationId: confirmationId,
            confirmationSentAt: new Date(),
          },
        });

        processed++;
        results.push({
          bookingId: booking.id,
          bookingNumber: booking.bookingNumber,
          confirmationId,
          status: 'success',
        });

        console.log(`✅ Auftragsbestätigung für ${booking.bookingNumber} erstellt`);
      } catch (error) {
        console.error(`❌ Fehler bei ${booking.bookingNumber}:`, error);
        results.push({
          bookingId: booking.id,
          bookingNumber: booking.bookingNumber,
          status: 'error',
          error: error instanceof Error ? error.message : 'Unknown error',
        });
      }
    }

    return NextResponse.json({
      success: true,
      processed,
      total: bookings.length,
      results,
    });
  } catch (error) {
    console.error('Contract check cron error:', error);
    return NextResponse.json(
      { error: 'Cron job failed' },
      { status: 500 }
    );
  }
}
