const CrmMpesaImportService = require('../services/CrmMpesaImportService');
const { AuditLog } = require('../models/foundation');
const { Op } = require('sequelize');

exports.runImport = async (req, res) => {
    try {
        const summary = await CrmMpesaImportService.fetchPayments();
        res.json({
            success: summary.errors.length === 0,
            message: summary.errors.length > 0 ? 'Import completed with warnings' : 'Import successful',
            data: summary
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getStatus = async (req, res) => {
    try {
        // Count stats from logs
        const today = new Date().toISOString().split('T')[0];
        const { Income } = require('../models/income');

        // Last sync status
        const lastSession = await AuditLog.findOne({
            where: { action: { [Op.like]: 'CRM_IMPORT%' } },
            order: [['createdAt', 'DESC']]
        });

        // Detailed metrics for today
        const importedToday = await Income.count({
            where: { crmSource: true, receivedDate: today }
        });

        const errorCount = await AuditLog.count({
            where: {
                action: 'CRM_IMPORT_ERROR',
                createdAt: { [Op.gte]: today }
            }
        });

        // Mock skipped for now as we don't log every skip individually or we need a specific log for session summary
        const skippedToday = 0;

        res.json({
            lastSync: lastSession ? lastSession.createdAt : null,
            status: lastSession ? (lastSession.action.includes('SUCCESS') ? 'Healthy' : 'Error') : 'Never Run',
            importedToday,
            errorCount,
            skippedToday
        });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getErrors = async (req, res) => {
    try {
        const errors = await AuditLog.findAll({
            where: { action: 'CRM_IMPORT_ERROR' },
            limit: 20,
            order: [['createdAt', 'DESC']]
        });
        res.json(errors);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
