import cron from 'node-cron';
import { emailSyncService } from '../lib/email-sync';
import { prisma } from '../lib/prisma';

console.log('🚀 E-Mail-Sync Cron-Job gestartet...\n');

// Sync alle 5 Minuten
cron.schedule('*/5 * * * *', async () => {
  console.log(`\n⏰ [${new Date().toLocaleString('de-DE')}] Starte E-Mail-Sync...`);
  
  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.');
      return;
    }

    console.log(`📍 Sync für ${locations.length} Location(s)...\n`);

    let totalNewEmails = 0;
    let totalNewBookings = 0;

    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, ${result.newBookings} neue Buchungen`);
        totalNewEmails += result.newEmails;
        totalNewBookings += result.newBookings;
      } else {
        console.log(`   ❌ Fehler: ${result.errors.join(', ')}`);
      }
    }

    console.log(`\n📊 Gesamt: ${totalNewEmails} E-Mails, ${totalNewBookings} Buchungen`);
    console.log('─'.repeat(60));
  } catch (error: any) {
    console.error('❌ Cron-Job Fehler:', error.message);
  }
});

console.log('✅ Cron-Job läuft - E-Mails werden alle 5 Minuten abgerufen');
console.log('   Drücken Sie CTRL+C zum Beenden\n');

// Sofort einmal ausführen beim Start
(async () => {
  console.log('🔄 Initialer E-Mail-Sync beim Start...\n');
  
  try {
    const locations = await prisma.location.findMany({
      where: { emailSyncEnabled: true },
      select: { id: true, name: true },
    });

    for (const location of locations) {
      console.log(`📍 ${location.name}...`);
      const result = await emailSyncService.syncLocationEmails(location.id);
      
      if (result.success) {
        console.log(`   ✅ ${result.newEmails} E-Mails, ${result.newBookings} Buchungen\n`);
      } else {
        console.log(`   ❌ ${result.errors.join(', ')}\n`);
      }
    }
  } catch (error: any) {
    console.error('❌ Initialer Sync Fehler:', error.message);
  }
})();

// Graceful shutdown
process.on('SIGINT', async () => {
  console.log('\n\n👋 Beende E-Mail-Sync Cron-Job...');
  await prisma.$disconnect();
  process.exit(0);
});
