"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPulseEvalData = 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 workspaceUtils_1 = require("./workspaceUtils");
// Helper function to get date range data for pulse eval count
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}`,
            count: 0,
        });
        currentDate.setUTCDate(currentDate.getUTCDate() + 1);
    }
    return days;
};
const getPulseEvalData = 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',
            };
        }
        const dateStart = (0, workspaceUtils_1.parseStartDate)(start, 7);
        const dateEnd = (0, workspaceUtils_1.parseEndDate)(end);
        let pulseEvalCount = 0;
        const pulseEvalLast7DaysData = getDateRangeData(dateStart, dateEnd);
        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 dateStartFormatted = dateStart.toISOString().replace('T', ' ').slice(0, 19);
            const dateEndFormatted = dateEnd.toISOString().replace('T', ' ').slice(0, 19);
            const scope = {
                start: dateStartFormatted,
                end: dateEndFormatted,
                projectIds,
                applicationIds: monitoredAppIds,
            };
            const countQuery = (0, evalResultsClickhouse_1.buildWorkspacePulseEvalCountSqlDenorm)(scope);
            const dailyQuery = (0, evalResultsClickhouse_1.buildWorkspacePulseEvalDailySqlDenorm)(scope);
            const [countResult, dailyResult] = await Promise.all([
                clickhouseService_1.clickHouseService.query(countQuery),
                clickhouseService_1.clickHouseService.query(dailyQuery),
            ]);
            pulseEvalCount = Number(countResult[0]?.total || 0);
            if (Array.isArray(dailyResult)) {
                for (const row of dailyResult) {
                    const date = row.date instanceof Date
                        ? row.date.toISOString().split('T')[0]
                        : String(row.date ?? '').slice(0, 10);
                    const dayData = pulseEvalLast7DaysData.find((d) => d.date === date);
                    if (dayData) {
                        dayData.count = Number(row.count || 0);
                    }
                }
            }
        }
        return {
            status: 1,
            response: {
                pulseEvalCount,
                pulseEvalLast7DaysData,
            },
        };
    }
    catch (error) {
        console.error('Error fetching pulse eval data:', error);
        return {
            status: 0,
            message: 'Error fetching pulse eval data',
            error,
        };
    }
};
exports.getPulseEvalData = getPulseEvalData;
//# sourceMappingURL=getPulseEvalData.js.map