"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPulseTracesStats = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const date_fns_1 = require("date-fns");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const evalResultsClickhouse_1 = require("../../services/evalResultsClickhouse");
const clickhouseService_1 = require("../../services/clickhouseService");
const getPulseTracesStats = 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 = start ? new Date(start) : (() => {
            const d = new Date();
            d.setDate(d.getDate() - 7);
            d.setUTCHours(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: {
                    totalTraces: 0,
                    totalTracesEvaluated: 0,
                },
            };
        }
        const dateStartFormatted = (0, date_fns_1.format)(dateStart, 'yyyy-MM-dd HH:mm:ss');
        const dateEndFormatted = (0, date_fns_1.format)(dateEnd, 'yyyy-MM-dd HH:mm:ss');
        const appIdsString = monitoredAppIds.map((id) => `'${id}'`).join(',');
        const totalTracesQuery = `
      SELECT COUNT(DISTINCT TraceId) as total
      FROM otel_traces
      WHERE ResourceAttributes['service.name'] IN (${appIdsString})
        AND Timestamp >= '${dateStartFormatted}'
        AND Timestamp <= '${dateEndFormatted}'
    `;
        const totalTracesEvaluatedQuery = (0, evalResultsClickhouse_1.buildWorkspacePulseTracesEvaluatedSqlDenorm)({
            start: dateStartFormatted,
            end: dateEndFormatted,
            projectIds,
            applicationIds: monitoredAppIds,
        });
        const [totalTracesResult, totalTracesEvaluatedResult] = await Promise.all([
            clickhouseService_1.clickHouseService.query(totalTracesQuery),
            clickhouseService_1.clickHouseService.query(totalTracesEvaluatedQuery),
        ]);
        const totalTraces = Number(totalTracesResult[0]?.total || 0);
        const totalTracesEvaluated = Number(totalTracesEvaluatedResult[0]?.total || 0);
        return {
            status: 1,
            response: {
                totalTraces,
                totalTracesEvaluated,
            },
        };
    }
    catch (error) {
        console.error('Error fetching pulse traces stats:', error);
        return {
            status: 0,
            message: 'Error fetching pulse traces stats',
            error,
        };
    }
};
exports.getPulseTracesStats = getPulseTracesStats;
//# sourceMappingURL=getPulseTracesStats.js.map