const { PrismaClient } = require('@prisma/client');
const { nextcloudCalendar } = require('./lib/nextcloud-calendar');

const prisma = new PrismaClient();

async function syncExistingBookings() {
  console.log('🔄 Synchronisiere bestehende Buchungen mit Nextcloud...\n');

  try {
    // 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\n`);

    if (bookings.length === 0) {
      console.log('ℹ️  Keine Buchungen zum Synchronisieren gefunden.');
      return;
    }

    let synced = 0;
    let failed = 0;

    for (const booking of bookings) {
      try {
        console.log(`📅 Synchronisiere: ${booking.bookingNumber} - ${booking.customerName}`);
        console.log(`   Event: ${new Date(booking.eventDate).toLocaleDateString('de-DE')}`);
        console.log(`   Standort: ${booking.location?.name || 'Unbekannt'}`);
        
        await nextcloudCalendar.syncBookingToCalendar(booking);
        synced++;
        console.log(`   ✅ Erfolgreich!\n`);
      } catch (error) {
        failed++;
        console.error(`   ❌ Fehler: ${error.message}\n`);
      }
    }

    console.log('─'.repeat(50));
    console.log(`✅ Erfolgreich synchronisiert: ${synced}`);
    console.log(`❌ Fehlgeschlagen: ${failed}`);
    console.log(`📊 Gesamt: ${bookings.length}`);
    console.log('\n🎉 Synchronisation abgeschlossen!');
    console.log('   Prüfen Sie Nextcloud → Kalender "Buchungen"');

  } catch (error) {
    console.error('❌ Fehler beim Synchronisieren:', error);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

syncExistingBookings()
  .catch((error) => {
    console.error('Fatal error:', error);
    process.exit(1);
  });
