"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PulseController = void 0;
const date_fns_1 = require("date-fns");
const drizzle_orm_1 = require("drizzle-orm");
const lodash_1 = __importDefault(require("lodash"));
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const clickhouse_1 = require("../../../util/clickhouse");
const pulseService_1 = require("../../services/pulseService");
const PulseController = {
    async getPulse(req, res) {
        try {
            logger_1.default.info('Pulse endpoint called');
            const pulseData = await pulseService_1.pulseService.getPulse();
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in pulse controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get pulse data',
                error: error.message,
            });
        }
    },
    async getDashboard(req, res) {
        try {
            const { type, start, end, applicationId, orgId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const db = await (0, database_1.getDb)();
            const application = await db
                .select()
                .from(tables_1.applicationsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, applicationId));
            if (application.length === 0) {
                res.json({
                    success: false,
                    message: 'Application not found',
                    error: 'Application not found',
                });
                return;
            }
            const dashboardData = await pulseService_1.pulseService.getDashboard({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                projectId: application?.[0]?.projectId,
                applicationIds: application.map((application) => application.id),
                operationType: 'llm',
                type: 'total',
                orgId: orgId,
            });
            res.json({
                success: true,
                data: dashboardData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in dashboard controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get dashboard data',
                error: error.message,
            });
        }
    },
    async getTotalRequests(req, res) {
        try {
            logger_1.default.info('Total requests endpoint called');
            const { projectId, type, start, end } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const totalRequests = await pulseService_1.pulseService.getTotalRequests({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                projectId: projectId,
                operationType: 'llm',
            });
            res.json({
                success: true,
                data: totalRequests,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in total requests controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total requests',
                error: error.message,
            });
        }
    },
    async getAverageRequestDuration(req, res) {
        try {
            logger_1.default.info('Average request duration endpoint called');
            const { projectId, type, start, end } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const averageRequestDuration = await pulseService_1.pulseService.getAverageRequestDuration({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                projectId: projectId,
                operationType: 'llm',
            });
            res.json({
                success: true,
                data: averageRequestDuration,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in average request duration controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get average request duration',
                error: error.message,
            });
        }
    },
    async getAverageTokensPerRequest(req, res) {
        try {
            logger_1.default.info('Average tokens per request endpoint called');
            const { projectId, type, start, end } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const averageTokensPerRequest = await pulseService_1.pulseService.getAverageTokensPerRequest({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                projectId: projectId,
                type: 'total',
            });
            res.json({
                success: true,
                data: averageTokensPerRequest,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in average tokens per request controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get average tokens per request',
                error: error.message,
            });
        }
    },
    async getAverageCostPerRequest(req, res) {
        try {
            logger_1.default.info('Average cost per request endpoint called');
            const { projectId, type, start, end } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const averageCostPerRequest = await pulseService_1.pulseService.getAverageCostPerRequest({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                projectId: projectId,
                operationType: 'llm',
            });
            res.json({
                success: true,
                data: averageCostPerRequest,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in average cost per request controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get average cost per request',
                error: error.message,
            });
        }
    },
    async getReports(req, res) {
        try {
            logger_1.default.info('Get Reports endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const db = await (0, database_1.getDb)();
            const applicationIds = [];
            if (applicationId
                && !lodash_1.default.isEmpty(applicationId)
                && applicationId !== 'undefined'
                && applicationId !== 'null') {
                applicationIds.push(applicationId);
            }
            if (lodash_1.default.isEmpty(applicationIds)) {
                const applicationsInProject = await db
                    .select({
                    id: tables_1.applicationsTable.id,
                })
                    .from(tables_1.applicationsTable)
                    .innerJoin(tables_1.pulseMonitoringTable, (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, tables_1.pulseMonitoringTable.applicationId))
                    .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId)))
                    .orderBy(tables_1.applicationsTable.createdAt);
                applicationIds.push(...applicationsInProject.map((application) => application.id));
            }
            const reports = await pulseService_1.pulseService.getReports({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                projectId: projectId,
                applicationIds,
                sorting: {
                    type: 'Timestamp',
                    direction: 'desc',
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get reports controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get reports',
                error: error.message,
            });
        }
    },
    async getReportData(req, res) {
        try {
            logger_1.default.info('Get Report Data endpoint called');
            const { traceId } = req?.params ?? {};
            if (!lodash_1.default.isString(traceId) || lodash_1.default.isEmpty(traceId?.trim())) {
                res.status(400).json({
                    success: false,
                    message: 'Invalid trace ID',
                    error: 'Invalid trace ID',
                });
                return;
            }
            const reportData = await pulseService_1.pulseService.getReportData({
                traceId,
            });
            res.json({
                success: true,
                data: reportData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get report data controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get report data',
                error: error.message,
            });
        }
    },
    async getTotalRecordsPass(req, res) {
        try {
            logger_1.default.info('Get Total Records Pass endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getTotalRecordsPass({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                projectId: projectId,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get total records pass controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total records pass',
                error: error.message,
            });
        }
    },
    async getTotalRecordsFail(req, res) {
        try {
            logger_1.default.info('Get Total Records Fail endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getTotalRecordsFail({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                projectId: projectId,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get total records fail controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total records fail',
                error: error.message,
            });
        }
    },
    async getTotalRecordsError(req, res) {
        try {
            logger_1.default.info('Get Total Records Error endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getTotalRecordsError({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                projectId: projectId,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get total records error controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total records error',
                error: error.message,
            });
        }
    },
    async getTotalSessionsPass(req, res) {
        try {
            logger_1.default.info('Get Total Sessions Pass endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getTotalSessionsPass({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                projectId: projectId,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get total sessions pass controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total sessions pass',
                error: error.message,
            });
        }
    },
    async getTotalSessionsFail(req, res) {
        try {
            logger_1.default.info('Get Total Sessions Fail endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getTotalSessionsFail({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                projectId: projectId,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get total sessions fail controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total sessions fail',
                error: error.message,
            });
        }
    },
    async getTotalSessionsError(req, res) {
        try {
            logger_1.default.info('Get Total Sessions Error endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getTotalSessionsError({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                projectId: projectId,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get total sessions error controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get total sessions error',
                error: error.message,
            });
        }
    },
    async getMetricFailureAnalysis(req, res) {
        try {
            logger_1.default.info('Get Metric Failure Analysis endpoint called');
            const { projectId, type, start, end, metricType, metricName, applicationId, categoryType, output, isRedteam = 0, detailTraceId, } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getMetricFailureAnalysis({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                categoryType: categoryType,
                metricType: metricType,
                metricName: metricName,
                projectId: projectId,
                applicationId: applicationId,
                output: output || '',
                isRedteam: clickhouse_1.ClickHouseHelper.safeConvertToNumber(isRedteam) ?? 0,
                detailTraceId: typeof detailTraceId === 'string' ? detailTraceId : undefined,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get metric failure analysis controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get metric failure analysis',
                error: error.message,
            });
        }
    },
    async getMetricFailureAnalysisSessions(req, res) {
        try {
            logger_1.default.info('Get Metric Failure Analysis Sessions endpoint called');
            const { projectId, type, start, end, metricType, metricName, applicationId, categoryType, output, detailSessionId, } = req?.query ?? {};
            let timeLimitType = type ?? '7D';
            const timeLimitStart = start ?? (0, date_fns_1.sub)(new Date(), { days: 7 }).toISOString();
            const timeLimitEnd = end ?? new Date().toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const { page = 1, limit = 10 } = req?.query ?? {};
            const reports = await pulseService_1.pulseService.getMetricFailureAnalysisSessions({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                page: clickhouse_1.ClickHouseHelper.safeConvertToNumber(page) ?? 1,
                limit: clickhouse_1.ClickHouseHelper.safeConvertToNumber(limit) ?? 10,
                categoryType: categoryType,
                metricType: metricType,
                metricName: metricName,
                projectId: projectId,
                applicationId: applicationId,
                output: output || '',
                detailSessionId: typeof detailSessionId === 'string' ? detailSessionId : undefined,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get metric failure analysis sessions controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get metric failure analysis sessions',
                error: error.message,
            });
        }
    },
    async getSpansUsage(req, res) {
        try {
            logger_1.default.info('Get Spans Usage endpoint called');
            const { orgId, type, start, end, dailyUsage } = req?.query ?? {};
            let timeLimitType = type ?? '30D';
            const timeLimitStart = start ?? (0, date_fns_1.startOfMonth)(new Date()).toISOString();
            const timeLimitEnd = end ?? (0, date_fns_1.endOfMonth)(new Date()).toISOString();
            if (timeLimitType === 'today' || timeLimitType === 'yesterday') {
                timeLimitType = '24H';
            }
            const shouldGetDailyUsage = dailyUsage === 'true';
            const reports = await pulseService_1.pulseService.getSpansUsage({
                timeLimit: {
                    start: (0, date_fns_1.format)(new Date(timeLimitStart), 'yyyy-MM-dd HH:mm:ss'),
                    end: (0, date_fns_1.format)(new Date(timeLimitEnd), 'yyyy-MM-dd HH:mm:ss'),
                    type: timeLimitType,
                },
                orgId: orgId,
                shouldGetDailyUsage,
            });
            res.json({
                success: true,
                data: reports,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get spans usage controller: ${error}`);
            res.json({
                success: false,
                message: 'Failed to get spans usage',
                error: error.message,
            });
        }
    },
};
exports.PulseController = PulseController;
//# sourceMappingURL=index.js.map