"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLatestAlertCondition = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const constants_1 = require("../../../constants");
const getLatestAlertCondition = async (params) => {
    try {
        const db = (0, database_1.getDb)();
        const { projectIds, applicationId, start, end } = params || {};
        if (!projectIds || projectIds.length === 0) {
            return {
                status: 0,
                message: 'Project IDs are required',
            };
        }
        // Build date filter conditions
        const dateStart = start ? new Date(start) : (() => {
            const d = new Date();
            d.setDate(d.getDate() - 7);
            d.setHours(0, 0, 0, 0);
            return d;
        })();
        const dateEnd = end ? new Date(end) : new Date();
        dateEnd.setHours(23, 59, 59, 999);
        // Filter alerts by type: SCOUT_FUNCTIONAL_EVALUATION or SCOUT_SECURITY_EVALUATION
        // Use sql.raw() to embed literal string values to avoid PostgreSQL parameter type issues
        // The values are from constants, so safe from SQL injection
        const functionalEvalType = constants_1.ALERT_TYPES.SCOUT_FUNCTIONAL_EVALUATION;
        const securityEvalType = constants_1.ALERT_TYPES.SCOUT_SECURITY_EVALUATION;
        const alertTypeConditions = (0, drizzle_orm_1.or)(drizzle_orm_1.sql.raw(`"monitoring_alerts"."alert"->>'type' = '${functionalEvalType}'`), drizzle_orm_1.sql.raw(`"monitoring_alerts"."alert"->>'type' = '${securityEvalType}'`));
        // Build where conditions
        const whereConditions = [
            (0, drizzle_orm_1.inArray)(tables_1.pulseMonitoringAlertsTable.projectId, projectIds),
            (0, drizzle_orm_1.gte)(tables_1.pulseAlertLogsTable.createdAt, dateStart),
            (0, drizzle_orm_1.lte)(tables_1.pulseAlertLogsTable.createdAt, dateEnd),
            alertTypeConditions,
        ];
        if (applicationId) {
            whereConditions.push((0, drizzle_orm_1.eq)(tables_1.pulseAlertLogsTable.applicationId, applicationId));
        }
        // Get latest alert log entry
        const latestAlert = await db
            .select({
            id: tables_1.pulseAlertLogsTable.id,
            alertId: tables_1.pulseAlertLogsTable.alertId,
            createdAt: tables_1.pulseAlertLogsTable.createdAt,
            alertName: tables_1.pulseMonitoringAlertsTable.name,
            alertCondition: tables_1.pulseMonitoringAlertsTable.condition,
            applicationId: tables_1.pulseAlertLogsTable.applicationId,
            applicationName: tables_1.applicationsTable.name,
        })
            .from(tables_1.pulseAlertLogsTable)
            .innerJoin(tables_1.pulseMonitoringAlertsTable, (0, drizzle_orm_1.eq)(tables_1.pulseAlertLogsTable.alertId, tables_1.pulseMonitoringAlertsTable.id))
            .innerJoin(tables_1.applicationsTable, (0, drizzle_orm_1.eq)(tables_1.pulseAlertLogsTable.applicationId, tables_1.applicationsTable.id))
            .where((0, drizzle_orm_1.and)(...whereConditions))
            .orderBy((0, drizzle_orm_1.desc)(tables_1.pulseAlertLogsTable.createdAt))
            .limit(1);
        // Get total alerts triggered count in the time range
        const totalAlertsResult = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.pulseAlertLogsTable)
            .innerJoin(tables_1.pulseMonitoringAlertsTable, (0, drizzle_orm_1.eq)(tables_1.pulseAlertLogsTable.alertId, tables_1.pulseMonitoringAlertsTable.id))
            .where((0, drizzle_orm_1.and)(...whereConditions));
        const totalAlertsTriggered = Number(totalAlertsResult[0]?.count || 0);
        if (latestAlert.length === 0) {
            return {
                status: 1,
                response: {
                    latestAlert: null,
                    totalAlertsTriggered: 0,
                },
            };
        }
        const alert = latestAlert[0];
        return {
            status: 1,
            response: {
                latestAlert: {
                    id: alert.id,
                    alertId: alert.alertId,
                    alertName: alert.alertName,
                    alertCondition: alert.alertCondition,
                    applicationName: alert.applicationName,
                    applicationId: alert.applicationId,
                    createdAt: alert.createdAt,
                },
                totalAlertsTriggered,
            },
        };
    }
    catch (error) {
        console.error('Error fetching latest alert condition:', error);
        return {
            status: 0,
            message: 'Error fetching latest alert condition',
            error,
        };
    }
};
exports.getLatestAlertCondition = getLatestAlertCondition;
//# sourceMappingURL=getLatestAlertCondition.js.map