"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPulseMetricsGraph = void 0;
/* eslint-disable @typescript-eslint/no-unused-vars */
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 workspaceUtils_1 = require("./workspaceUtils");
// Helper function to get date range data for pulse (uses UTC)
const getDateRangeData = (startDate, endDate) => {
    const days = [];
    const start = new Date(startDate);
    start.setUTCHours(0, 0, 0, 0);
    const end = new Date(endDate);
    end.setUTCHours(23, 59, 59, 999);
    const currentDate = new Date(start);
    while (currentDate <= end) {
        const year = currentDate.getUTCFullYear();
        const month = String(currentDate.getUTCMonth() + 1).padStart(2, '0');
        const day = String(currentDate.getUTCDate()).padStart(2, '0');
        days.push({
            date: `${year}-${month}-${day}`,
            total: 0,
            pass: 0,
            fail: 0,
        });
        currentDate.setUTCDate(currentDate.getUTCDate() + 1);
    }
    return days;
};
const getPulseMetricsGraph = 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',
            };
        }
        // Parse dates using shared utility (UTC)
        const dateStart = (0, workspaceUtils_1.parseStartDate)(start, 7);
        const dateEnd = (0, workspaceUtils_1.parseEndDate)(end);
        // Get applications with monitoring enabled
        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) {
            const emptyData = getDateRangeData(dateStart, dateEnd);
            return {
                status: 1,
                response: {
                    graphData: emptyData,
                },
            };
        }
        const dateStartFormatted = dateStart.toISOString().replace('T', ' ').slice(0, 19);
        const dateEndFormatted = dateEnd.toISOString().replace('T', ' ').slice(0, 19);
        const query = (0, evalResultsClickhouse_1.buildWorkspacePulseMetricsGraphSqlDenorm)({
            start: dateStartFormatted,
            end: dateEndFormatted,
            projectIds,
            applicationIds: monitoredAppIds,
        });
        const result = await clickhouseService_1.clickHouseService.query(query);
        const graphData = getDateRangeData(dateStart, dateEnd);
        const dateStats = new Map();
        for (const dayData of graphData) {
            dateStats.set(dayData.date, { total: 0, pass: 0, fail: 0 });
        }
        if (Array.isArray(result) && result.length > 0) {
            for (const row of result) {
                const date = row.date instanceof Date
                    ? row.date.toISOString().split('T')[0]
                    : String(row.date ?? '').slice(0, 10);
                const stats = dateStats.get(date);
                if (stats) {
                    stats.total = Number(row.total ?? 0);
                    stats.pass = Number(row.pass ?? 0);
                    stats.fail = Number(row.fail ?? 0);
                }
            }
        }
        for (const dayData of graphData) {
            const stats = dateStats.get(dayData.date);
            if (stats) {
                dayData.total = stats.total;
                dayData.pass = stats.pass;
                dayData.fail = stats.fail;
            }
        }
        return {
            status: 1,
            response: {
                graphData,
            },
        };
    }
    catch (error) {
        console.error('Error fetching pulse metrics graph:', error);
        return {
            status: 0,
            message: 'Error fetching pulse metrics graph',
            error,
        };
    }
};
exports.getPulseMetricsGraph = getPulseMetricsGraph;
//# sourceMappingURL=getPulseMetricsGraph.js.map