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 POST(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || session.user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    console.log('🔄 Synchronisiere bestehende Buchungen mit Nextcloud...\n');

    // Hole alle bestätigten Buchungen
    const bookings = await prisma.booking.findMany({
      where: {
        status: {
          in: ['RESERVED', 'CONFIRMED'],
        },
      },
      include: {
        location: true,
        photobox: true,
      },
      orderBy: {
        eventDate: 'asc',
      },
    });

    console.log(`📊 Gefunden: ${bookings.length} Buchungen`);

    if (bookings.length === 0) {
      return NextResponse.json({
        success: true,
        message: 'Keine Buchungen zum Synchronisieren gefunden.',
        synced: 0,
        failed: 0,
        total: 0,
      });
    }

    let synced = 0;
    let failed = 0;
    const errors: any[] = [];

    for (const booking of bookings) {
      try {
        console.log(`📅 Synchronisiere: ${booking.bookingNumber} - ${booking.customerName}`);
        
        await nextcloudCalendar.syncBookingToCalendar(booking);
        synced++;
        console.log(`   ✅ Erfolgreich!`);
      } catch (error: any) {
        failed++;
        console.error(`   ❌ Fehler: ${error.message}`);
        errors.push({
          bookingNumber: booking.bookingNumber,
          customerName: booking.customerName,
          error: error.message,
        });
      }
    }

    console.log('─'.repeat(50));
    console.log(`✅ Erfolgreich synchronisiert: ${synced}`);
    console.log(`❌ Fehlgeschlagen: ${failed}`);
    console.log(`📊 Gesamt: ${bookings.length}`);

    return NextResponse.json({
      success: true,
      synced,
      failed,
      total: bookings.length,
      errors: errors.length > 0 ? errors : undefined,
    });

  } catch (error: any) {
    console.error('❌ Fehler beim Synchronisieren:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to sync bookings' },
      { status: 500 }
    );
  }
}
