"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkEligibility = exports.scoreLeadAI = exports.generateReport = exports.createDSAPayout = exports.convertLeadToFile = void 0;
const database_1 = require("../config/database");
const idGenerator_1 = require("../utils/idGenerator");
// Convert lead to file
const convertLeadToFile = async (leadId, fileType, dsaCode, convertedBy) => {
    // Generate file number
    const fileNumber = await (0, idGenerator_1.generateFileNumber)();
    const result = await (0, database_1.query)(`UPDATE leads 
     SET file_number = $1, 
         updated_at = CURRENT_TIMESTAMP
     WHERE id = $2
     RETURNING *`, [fileNumber, leadId]);
    if (result.rows.length === 0) {
        throw new Error('Lead not found');
    }
    // Log activity
    await (0, database_1.query)(`INSERT INTO activities (lead_id, activity_type, title, description, performed_by)
     VALUES ($1, $2, $3, $4, $5)`, [leadId, 'FILE_CREATED', 'File Created', `File ${fileNumber} created`, convertedBy]);
    return result.rows[0];
};
exports.convertLeadToFile = convertLeadToFile;
// DSA Payout management
const createDSAPayout = async (leadId, dsaId, amount, createdBy) => {
    const result = await (0, database_1.query)(`INSERT INTO payouts (lead_id, dsa_id, amount, created_by)
     VALUES ($1, $2, $3, $4)
     RETURNING *`, [leadId, dsaId, amount, createdBy]);
    return result.rows[0];
};
exports.createDSAPayout = createDSAPayout;
// Reports generation
const generateReport = async (reportType, startDate, endDate) => {
    let reportData = {};
    switch (reportType) {
        case 'daily':
            reportData = await (0, database_1.query)(`SELECT COUNT(*) as total_leads, 
                SUM(CASE WHEN primary_status = 'Open' THEN 1 ELSE 0 END) as open_leads,
                SUM(CASE WHEN primary_status = 'Closed' THEN 1 ELSE 0 END) as closed_leads
         FROM leads 
         WHERE DATE(created_at) = CURRENT_DATE`);
            break;
        case 'weekly':
            reportData = await (0, database_1.query)(`SELECT COUNT(*) as total_leads,
                SUM(loan_amount) as total_loan_amount
         FROM leads 
         WHERE created_at >= CURRENT_DATE - INTERVAL '7 days'`);
            break;
        case 'monthly':
            reportData = await (0, database_1.query)(`SELECT COUNT(*) as total_leads,
                SUM(loan_amount) as total_loan_amount,
                AVG(loan_amount) as avg_loan_amount
         FROM leads 
         WHERE DATE_TRUNC('month', created_at) = DATE_TRUNC('month', CURRENT_DATE)`);
            break;
    }
    return reportData.rows[0];
};
exports.generateReport = generateReport;
// AI Lead Scoring (stub)
const scoreLeadAI = async (leadId) => {
    // AI lead scoring stub
    // In production, use ML model to score leads based on various factors
    const mockScore = Math.floor(Math.random() * 100);
    const mockFactors = {
        income: 0.3,
        creditHistory: 0.25,
        loanAmount: 0.2,
        employment: 0.15,
        assets: 0.1
    };
    return {
        leadId,
        score: mockScore,
        factors: mockFactors,
        recommendation: mockScore > 70 ? 'High Priority' : mockScore > 40 ? 'Medium Priority' : 'Low Priority'
    };
};
exports.scoreLeadAI = scoreLeadAI;
// Eligibility Engine (stub)
const checkEligibility = async (leadId) => {
    const lead = await (0, database_1.query)('SELECT * FROM leads WHERE id = $1', [leadId]);
    if (lead.rows.length === 0) {
        throw new Error('Lead not found');
    }
    // Eligibility check stub
    const mockEligibility = {
        eligible: true,
        maxLoanAmount: 5000000,
        interestRate: 8.5,
        tenure: 240,
        reasons: ['Good credit score', 'Stable income', 'Low debt-to-income ratio']
    };
    return mockEligibility;
};
exports.checkEligibility = checkEligibility;
