const cron = require('node-cron');
const CrmMpesaImportService = require('../services/CrmMpesaImportService');
const { sendEmail } = require('../services/emailService');

const initCrmImportJob = () => {
    console.log('⏰ [Job] CRM Import Scheduler initialized (00:00 Daily)');

    // Run at Midnight
    cron.schedule('0 0 * * *', async () => {
        console.log('🚀 [Job] Starting daily CRM import sync...');

        try {
            const summary = await CrmMpesaImportService.fetchPayments();

            const adminEmail = process.env.FINANCE_ADMIN_EMAIL || 'finance@youbroadband.co.ke';

            await sendEmail({
                email: adminEmail,
                subject: `[FinancePro] Daily CRM Sync Report - ${new Date().toLocaleDateString()}`,
                html: `
          <div style="font-family: sans-serif; max-width: 600px; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden;">
            <div style="background: #1e293b; padding: 24px; color: white;">
              <h1 style="margin: 0; font-size: 20px;">Daily CRM Import Summary</h1>
            </div>
            <div style="padding: 24px;">
              <div style="display: flex; gap: 16px; margin-bottom: 24px;">
                <div style="flex: 1; background: #f8fafc; padding: 16px; border-radius: 8px; text-align: center;">
                  <span style="display: block; font-size: 12px; color: #64748b; font-weight: bold; text-transform: uppercase;">Imported</span>
                  <span style="font-size: 24px; font-weight: 800; color: #10b981;">${summary.imported}</span>
                </div>
                <div style="flex: 1; background: #f8fafc; padding: 16px; border-radius: 8px; text-align: center;">
                  <span style="display: block; font-size: 12px; color: #64748b; font-weight: bold; text-transform: uppercase;">Skipped</span>
                  <span style="font-size: 24px; font-weight: 800; color: #64748b;">${summary.skipped}</span>
                </div>
              </div>
              
              ${summary.errors.length > 0 ? `
                <div style="background: #fef2f2; border: 1px solid #fee2e2; padding: 16px; border-radius: 8px;">
                  <h3 style="margin: 0 0 8px 0; color: #991b1b; font-size: 14px;">Import Warnings (${summary.errors.length})</h3>
                  <ul style="margin: 0; padding-left: 20px; font-size: 13px; color: #b91c1c;">
                    ${summary.errors.slice(0, 5).map(err => `<li>${err}</li>`).join('')}
                    ${summary.errors.length > 5 ? '<li>...and more</li>' : ''}
                  </ul>
                </div>
              ` : `
                <div style="background: #ecfdf5; border: 1px solid #d1fae5; padding: 16px; border-radius: 8px; text-align: center;">
                  <p style="margin: 0; color: #065f46; font-size: 14px; font-weight: bold;">✅ Sync completed with zero errors.</p>
                </div>
              `}
              
              <div style="margin-top: 24px; padding-top: 24px; border-top: 1px solid #f1f5f9; font-size: 12px; color: #94a3b8; text-align: center;">
                Automated by Enterprise FinancePro System
              </div>
            </div>
          </div>
        `
            });

            console.log(`✅ [Job] CRM Import finished. Imported: ${summary.imported}, Skipped: ${summary.skipped}`);

        } catch (err) {
            console.error('❌ [Job] Scheduled CRM Import Failed:', err);
        }
    });
};

module.exports = { initCrmImportJob };
