import { PrismaClient } from '@prisma/client';
import { emailSyncService } from '../lib/email-sync';

const prisma = new PrismaClient();

async function manualEmailSync() {
  console.log('🔄 Manueller E-Mail-Sync gestartet...\n');

  try {
    const locations = await prisma.location.findMany({
      where: { emailSyncEnabled: true },
      select: { id: true, name: true, slug: true },
    });

    if (locations.length === 0) {
      console.log('⚠️  Keine Locations mit aktiviertem E-Mail-Sync gefunden.\n');
      console.log('💡 Bitte aktivieren Sie E-Mail-Sync in den Location-Einstellungen.\n');
      return;
    }

    console.log(`📍 Gefunden: ${locations.length} Location(s) mit E-Mail-Sync\n`);

    let totalNewEmails = 0;
    let totalNewBookings = 0;
    const results = [];

    for (const location of locations) {
      console.log(`🔄 ${location.name} (${location.slug})...`);
      
      const result = await emailSyncService.syncLocationEmails(location.id);
      
      if (result.success) {
        console.log(`   ✅ ${result.newEmails} neue E-Mails`);
        console.log(`   ✅ ${result.newBookings} neue Buchungen\n`);
        totalNewEmails += result.newEmails;
        totalNewBookings += result.newBookings;
      } else {
        console.log(`   ❌ Fehler:`);
        result.errors.forEach(err => console.log(`      - ${err}`));
        console.log('');
      }

      results.push({
        location: location.name,
        ...result,
      });
    }

    console.log('─'.repeat(60));
    console.log('📊 Zusammenfassung:');
    console.log(`   Locations: ${locations.length}`);
    console.log(`   Neue E-Mails: ${totalNewEmails}`);
    console.log(`   Neue Buchungen: ${totalNewBookings}`);
    console.log('─'.repeat(60));

    if (totalNewBookings > 0) {
      console.log('\n✅ Neue Buchungen im Dashboard verfügbar!');
      console.log('   → http://localhost:3000/dashboard/bookings\n');
    }

  } catch (error: any) {
    console.error('❌ Fehler beim E-Mail-Sync:', error.message);
    throw error;
  } finally {
    await prisma.$disconnect();
  }
}

manualEmailSync();
