"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reopenLead = exports.closeLead = exports.getAuditLogs = exports.logAudit = void 0;
const database_1 = require("../config/database");
const logAudit = async (tableName, recordId, action, oldValues, newValues, performedBy, ipAddress) => {
    await (0, database_1.query)(`INSERT INTO audit_logs (table_name, record_id, action, old_values, new_values, performed_by, ip_address)
     VALUES ($1, $2, $3, $4, $5, $6, $7)`, [tableName, recordId, action, JSON.stringify(oldValues), JSON.stringify(newValues), performedBy, ipAddress]);
};
exports.logAudit = logAudit;
const getAuditLogs = async (tableName, recordId) => {
    let queryText = `
    SELECT a.*, u.name as performed_by_name
    FROM audit_logs a
    LEFT JOIN users u ON a.performed_by = u.id
    WHERE 1=1
  `;
    const params = [];
    if (tableName) {
        params.push(tableName);
        queryText += ` AND a.table_name = $${params.length}`;
    }
    if (recordId) {
        params.push(recordId);
        queryText += ` AND a.record_id = $${params.length}`;
    }
    queryText += ' ORDER BY a.performed_at DESC LIMIT 100';
    const result = await (0, database_1.query)(queryText, params);
    return result.rows;
};
exports.getAuditLogs = getAuditLogs;
const closeLead = async (leadId, closeReason, subStatus, closedBy) => {
    const oldLead = await (0, database_1.query)('SELECT * FROM leads WHERE id = $1', [leadId]);
    const result = await (0, database_1.query)(`UPDATE leads 
     SET primary_status = 'Closed', 
         sub_status = $1, 
         close_reason = $2,
         closed_at = CURRENT_TIMESTAMP,
         closed_by = $3,
         updated_at = CURRENT_TIMESTAMP
     WHERE id = $4
     RETURNING *`, [subStatus, closeReason, closedBy, leadId]);
    if (result.rows.length === 0) {
        throw new Error('Lead not found');
    }
    // Log audit
    await (0, exports.logAudit)('leads', leadId, 'UPDATE', oldLead.rows[0], result.rows[0], closedBy);
    // 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, 'LEAD_CLOSED', 'Lead Closed', `Lead closed: ${closeReason}`, closedBy]);
    return result.rows[0];
};
exports.closeLead = closeLead;
const reopenLead = async (leadId, reopenedBy) => {
    const oldLead = await (0, database_1.query)('SELECT * FROM leads WHERE id = $1', [leadId]);
    const result = await (0, database_1.query)(`UPDATE leads 
     SET primary_status = 'Open',
         closed_at = NULL,
         closed_by = NULL,
         updated_at = CURRENT_TIMESTAMP
     WHERE id = $1
     RETURNING *`, [leadId]);
    if (result.rows.length === 0) {
        throw new Error('Lead not found');
    }
    // Log audit
    await (0, exports.logAudit)('leads', leadId, 'UPDATE', oldLead.rows[0], result.rows[0], reopenedBy);
    // 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, 'LEAD_REOPENED', 'Lead Reopened', 'Lead was reopened', reopenedBy]);
    return result.rows[0];
};
exports.reopenLead = reopenLead;
