"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getBreachedPendings = exports.escalatePending = exports.updatePending = exports.createPending = exports.getAllPendings = void 0;
const database_1 = require("../config/database");
const getAllPendings = async (filters) => {
    let queryText = `
    SELECT p.*, 
           l.lead_id,
           u1.name as assigned_to_name,
           u2.name as created_by_name,
           CASE 
             WHEN p.sla_breach_at < CURRENT_TIMESTAMP AND p.status != 'Resolved' THEN true
             ELSE false
           END as is_breached
    FROM pendings p
    LEFT JOIN leads l ON p.lead_id = l.id
    LEFT JOIN users u1 ON p.assigned_to = u1.id
    LEFT JOIN users u2 ON p.created_by = u2.id
    ORDER BY p.created_at DESC
  `;
    const result = await (0, database_1.query)(queryText);
    return result.rows;
};
exports.getAllPendings = getAllPendings;
const createPending = async (leadId, pendingType, description, dueDate, assignedTo, createdBy, slaHours = 24) => {
    const result = await (0, database_1.query)(`INSERT INTO pendings (lead_id, pending_type, description, due_date, assigned_to, created_by, sla_hours)
     VALUES ($1, $2, $3, $4, $5, $6, $7)
     RETURNING *`, [leadId, pendingType, description, dueDate, assignedTo, createdBy, slaHours]);
    return result.rows[0];
};
exports.createPending = createPending;
const updatePending = async (id, data) => {
    const fields = [];
    const values = [];
    let paramIndex = 1;
    if (data.status) {
        fields.push(`status = $${paramIndex++}`);
        values.push(data.status);
        if (data.status === 'Resolved') {
            fields.push(`resolved_at = CURRENT_TIMESTAMP`);
        }
    }
    if (data.description) {
        fields.push(`description = $${paramIndex++}`);
        values.push(data.description);
    }
    if (fields.length === 0) {
        throw new Error('No fields to update');
    }
    values.push(id);
    const result = await (0, database_1.query)(`UPDATE pendings SET ${fields.join(', ')} WHERE id = $${paramIndex} RETURNING *`, values);
    if (result.rows.length === 0) {
        throw new Error('Pending not found');
    }
    return result.rows[0];
};
exports.updatePending = updatePending;
const escalatePending = async (id, escalatedTo, escalatedBy) => {
    const result = await (0, database_1.query)(`UPDATE pendings 
     SET is_escalated = true,
         escalated_to = $1,
         escalated_at = CURRENT_TIMESTAMP
     WHERE id = $2
     RETURNING *`, [escalatedTo, id]);
    if (result.rows.length === 0) {
        throw new Error('Pending not found');
    }
    // Log activity
    const pending = result.rows[0];
    await (0, database_1.query)(`INSERT INTO activities (lead_id, activity_type, title, description, performed_by)
     VALUES ($1, $2, $3, $4, $5)`, [pending.lead_id, 'PENDING_ESCALATED', 'Pending Escalated', `Pending item escalated due to SLA breach`, escalatedBy]);
    return result.rows[0];
};
exports.escalatePending = escalatePending;
const getBreachedPendings = async () => {
    const result = await (0, database_1.query)(`
    SELECT p.*, 
           l.lead_id,
           u.name as assigned_to_name
    FROM pendings p
    LEFT JOIN leads l ON p.lead_id = l.id
    LEFT JOIN users u ON p.assigned_to = u.id
    WHERE p.sla_breach_at < CURRENT_TIMESTAMP 
      AND p.status != 'Resolved'
      AND p.is_escalated = false
    ORDER BY p.sla_breach_at ASC
  `);
    return result.rows;
};
exports.getBreachedPendings = getBreachedPendings;
