const puppeteer = require('puppeteer');
const { Income, IncomeCategory } = require('../models/income');
const { SystemSetting } = require('../models/settings');
const { logAction } = require('../utils/logger');
const { Op } = require('sequelize');

class CrmMpesaImportService {
    async fetchPayments() {
        const summary = {
            imported: 0,
            skipped: 0,
            errors: [],
            startTime: new Date(),
            endTime: null
        };

        let browser;
        try {
            // 1. Resolve Credentials (DB takes priority, then .env)
            const settings = await SystemSetting.findAll();
            const config = {};
            settings.forEach(s => config[s.key] = s.value);

            const username = config.CRM_ADMIN_USER || process.env.CRM_ADMIN_USER;
            const password = config.CRM_ADMIN_PASS || process.env.CRM_ADMIN_PASS;
            const loginUrl = config.CRM_LOGIN_URL || process.env.CRM_LOGIN_URL || 'https://crm.youbroadband.co.ke/login';

            if (!username || !password) {
                throw new Error('CRM credentials not configured (Dashboard or .env)');
            }

            // 2. Launch Browser
            browser = await puppeteer.launch({
                headless: 'new',
                args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
            });

            const page = await browser.newPage();
            await page.setViewport({ width: 1280, height: 800 });

            // 3. Login
            console.log(`[CRM Import] Attempting login at ${loginUrl}`);
            await page.goto(loginUrl, { waitUntil: 'networkidle2', timeout: 60000 });

            console.log('[CRM Import] Filling login form...');
            await page.type('input[name="login"]', username);
            await page.type('input[name="password"]', password);
            await Promise.all([
                page.click('button[type="submit"]'),
                page.waitForNavigation({ waitUntil: 'networkidle2' })
            ]);

            // 4. Navigate to Mpesa Billing
            const billingUrl = 'https://crm.youbroadband.co.ke/dashboard/billing/mpesa';
            await page.goto(billingUrl, { waitUntil: 'networkidle2' });

            // 5. Scrape Table Data
            console.log(`[CRM Import] Scraping table at ${billingUrl}`);
            const payments = await page.evaluate(() => {
                const rows = Array.from(document.querySelectorAll('table tr')).slice(1);
                return rows.map(row => {
                    const cells = row.querySelectorAll('td');
                    if (cells.length < 6) return null;
                    return {
                        amount: cells[2].innerText.trim().replace(/[^0-9.]/g, ''),
                        reference: cells[3].innerText.trim(),
                        date: cells[4].innerText.trim()
                    };
                }).filter(p => p !== null);
            });

            console.log(`[CRM Import] Total payments scraped: ${payments.length}`);
            if (payments.length > 0) {
                console.log(`[CRM Import] Sample payment: ${JSON.stringify(payments[0])}`);
            }

            // 6. Process Records
            const todayString = new Date().toISOString().split('T')[0];
            let category = await IncomeCategory.findOne({ where: { name: 'M-Pesa (CRM)' } });
            if (!category) {
                category = await IncomeCategory.create({
                    name: 'M-Pesa (CRM)',
                    description: 'Automated CRM Sync'
                });
            }

            for (const p of payments) {
                try {
                    // Date Filter: Only today's records
                    if (!p.date.includes(todayString)) continue;

                    // Duplicate Check
                    const existing = await Income.findOne({
                        where: {
                            reference: p.reference,
                            crmSource: true
                        }
                    });

                    if (existing) {
                        summary.skipped++;
                        continue;
                    }

                    // Insert Record
                    await Income.create({
                        amount: parseFloat(p.amount),
                        reference: p.reference,
                        source: 'CRM',
                        crmSource: true,
                        receivedDate: todayString,
                        paymentMethod: 'M-Pesa',
                        incomeCategoryId: category.id,
                        isReadOnly: true,
                        notes: `CRM Sync: ${p.reference}`,
                        createdBy: null
                    });

                    summary.imported++;
                    await logAction('SYSTEM', 'CRM_IMPORT_SUCCESS', 'INCOME', { ref: p.reference }, 'Scraper');

                } catch (itemErr) {
                    summary.errors.push(`Record ${p.reference} failed: ${itemErr.message}`);
                }
            }

        } catch (globalErr) {
            console.error('[CRM Import] Global Failure:', globalErr);
            summary.errors.push(`Global Task Error: ${globalErr.message}`);
            await logAction('SYSTEM', 'CRM_IMPORT_ERROR', 'ERROR', { msg: globalErr.message }, 'Scraper');
        } finally {
            if (browser) await browser.close();
            summary.endTime = new Date();
        }

        return summary;
    }
}

module.exports = new CrmMpesaImportService();
