"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPulseTopMetricFailures = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const evalResultsClickhouse_1 = require("../../services/evalResultsClickhouse");
const clickhouseService_1 = require("../../services/clickhouseService");
const getPulseTopMetricFailures = async (params) => {
    try {
        const db = (0, database_1.getDb)();
        const { projectIds, applicationId, start, end, limit = 5 } = params || {};
        if (!projectIds || projectIds.length === 0) {
            return {
                status: 0,
                message: 'Project IDs are required',
            };
        }
        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);
        const monitoredAppsWhereConditions = [(0, drizzle_orm_1.inArray)(tables_1.applicationsTable.projectId, projectIds)];
        if (applicationId) {
            monitoredAppsWhereConditions.push((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, applicationId));
        }
        const monitoredApps = await db
            .select({
            applicationId: tables_1.pulseMonitoringTable.applicationId,
        })
            .from(tables_1.pulseMonitoringTable)
            .innerJoin(tables_1.applicationsTable, (0, drizzle_orm_1.eq)(tables_1.pulseMonitoringTable.applicationId, tables_1.applicationsTable.id))
            .where((0, drizzle_orm_1.and)(...monitoredAppsWhereConditions));
        const monitoredAppIds = monitoredApps.map((app) => app.applicationId);
        if (monitoredAppIds.length === 0) {
            return {
                status: 1,
                response: {
                    topFailures: [],
                },
            };
        }
        const dateStartFormatted = dateStart.toISOString().replace('T', ' ').slice(0, 19);
        const dateEndFormatted = dateEnd.toISOString().replace('T', ' ').slice(0, 19);
        const query = (0, evalResultsClickhouse_1.buildWorkspacePulseTopFailuresSqlDenorm)({
            start: dateStartFormatted,
            end: dateEndFormatted,
            projectIds,
            applicationIds: monitoredAppIds,
            limit: Math.max(1, Number(limit) || 5),
        });
        const result = await clickhouseService_1.clickHouseService.query(query);
        const topFailures = (result ?? []).map((row) => {
            const total = Number(row.total ?? 0);
            const failed = Number(row.failed ?? 0);
            const passed = Number(row.passed ?? 0);
            return {
                metricName: row.metricName || 'Unknown',
                total,
                failed,
                passed,
                failureRate: total > 0 ? (failed / total) * 100 : 0,
            };
        });
        return {
            status: 1,
            response: {
                topFailures,
            },
        };
    }
    catch (error) {
        console.error('Error fetching pulse top metric failures:', error);
        return {
            status: 0,
            message: 'Error fetching pulse top metric failures',
            error,
        };
    }
};
exports.getPulseTopMetricFailures = getPulseTopMetricFailures;
//# sourceMappingURL=getPulseTopMetricFailures.js.map