"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PulseGraphController = 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 pulseService_1 = require("../../services/pulseService");
const PulseGraphController = {
    async getGraphRequestPerTime(req, res) {
        try {
            logger_1.default.info('Graph request per time 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 db = await (0, database_1.getDb)();
            const applicationsInProject = await db
                .select()
                .from(tables_1.applicationsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId));
            const applicationIds = applicationsInProject.map((application) => application.id);
            if (lodash_1.default.isEmpty(applicationId) && lodash_1.default.isEmpty(applicationIds)) {
                res.status(400).json({
                    success: false,
                    message: 'No application found in the project',
                });
                return;
            }
            const pulseData = await pulseService_1.pulseService.getGraphRequestPerTime({
                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,
                applicationId: applicationId,
                applicationIds,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in graph request per time controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get graph request per time data',
                error: error.message,
            });
        }
    },
    async getTotalRecords(req, res) {
        try {
            logger_1.default.info('Total records 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 pulseData = await pulseService_1.pulseService.getTotalRecords({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in total records controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get total records data',
                error: error.message,
            });
        }
    },
    /** Track chart: current health score (line chart) – returns only traces time-series for health % */
    async getCurrentHealthScore(req, res) {
        try {
            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 full = await pulseService_1.pulseService.getTotalRecords({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: {
                    traces_chart_data: full?.traces_chart_data ?? [],
                },
            });
        }
        catch (error) {
            logger_1.default.error(`Error in current health score controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get current health score data',
                error: error.message,
            });
        }
    },
    /** Track chart: sessions evaluated (donut) – returns only sessions totals */
    async getSessionsEvaluated(req, res) {
        try {
            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 full = await pulseService_1.pulseService.getTotalRecords({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: {
                    sessions_total_requests: full?.sessions_total_requests ?? 0,
                    sessions_total_success: full?.sessions_total_success ?? 0,
                    sessions_total_failures: full?.sessions_total_failures ?? 0,
                    sessions_total_errors: full?.sessions_total_errors ?? 0,
                },
            });
        }
        catch (error) {
            logger_1.default.error(`Error in sessions evaluated controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get sessions evaluated data',
                error: error.message,
            });
        }
    },
    /** Track chart: traces evaluated (donut) – returns only traces totals */
    async getTracesEvaluated(req, res) {
        try {
            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 full = await pulseService_1.pulseService.getTotalRecords({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: {
                    traces_total_requests: full?.traces_total_requests ?? 0,
                    traces_total_success: full?.traces_total_success ?? 0,
                    traces_total_failures: full?.traces_total_failures ?? 0,
                    traces_total_errors: full?.traces_total_errors ?? 0,
                },
            });
        }
        catch (error) {
            logger_1.default.error(`Error in traces evaluated controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get traces evaluated data',
                error: error.message,
            });
        }
    },
    async getMetricFailureAnalysisTotal(req, res) {
        try {
            logger_1.default.info('Metric failure analysis total 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 pulseData = await pulseService_1.pulseService.getMetricFailureAnalysisTotal({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric failure analysis total controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric failure analysis total data',
                error: error.message,
            });
        }
    },
    async getMetricFailureAnalysisTotalSessions(req, res) {
        try {
            logger_1.default.info('Metric failure analysis total sessions 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 pulseData = await pulseService_1.pulseService.getMetricFailureAnalysisTotalSessions({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric failure analysis total sessions controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric failure analysis total sessions data',
                error: error.message,
            });
        }
    },
    async getMetricFailureAnalysisSuccess(req, res) {
        try {
            logger_1.default.info('Metric failure analysis success 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 pulseData = await pulseService_1.pulseService.getMetricFailureAnalysisSuccess({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric failure analysis success controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric failure analysis success data',
                error: error.message,
            });
        }
    },
    async getMetricFailureAnalysisFailure(req, res) {
        try {
            logger_1.default.info('Metric failure analysis failure 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 pulseData = await pulseService_1.pulseService.getMetricFailureAnalysisFailure({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric failure analysis failure controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric failure analysis failure data',
                error: error.message,
            });
        }
    },
    /** Board chart: evaluation coverage donut – evaluated vs non-evaluated sessions */
    async getEvaluationCoverage(req, res) {
        try {
            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 full = await pulseService_1.pulseService.getTotalRecords({
                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,
                applicationId: applicationId,
            });
            const evaluatedSessions = full?.sessions_total_requests ?? 0;
            const nonEvaluatedSessions = 0;
            res.json({
                success: true,
                data: {
                    evaluatedSessions,
                    nonEvaluatedSessions,
                    sessions_chart_data: full?.sessions_chart_data ?? [],
                },
            });
        }
        catch (error) {
            logger_1.default.error(`Error in getEvaluationCoverage: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get evaluation coverage data',
                error: error.message,
            });
        }
    },
    async getMetricVolumeAnalysis(req, res) {
        try {
            logger_1.default.info('Metric volume analysis 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 pulseData = await pulseService_1.pulseService.getMetricVolumeAnalysis({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric volume analysis controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric volume analysis data',
                error: error.message,
            });
        }
    },
    async getAudioMetricAnalysis(req, res) {
        try {
            logger_1.default.info('Metric analysis endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            const { metricName } = req?.params ?? {};
            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 pulseData = await pulseService_1.pulseService.getAudioMetricAnalysis({
                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,
                applicationId: applicationId,
                metricName: metricName,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric analysis controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric analysis data',
                error: error.message,
            });
        }
    },
    async getAudioMetricTimeAnalysis(req, res) {
        try {
            logger_1.default.info('Metric time analysis endpoint called');
            const { projectId, type, start, end, applicationId } = req?.query ?? {};
            const { metricName } = req?.params ?? {};
            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 pulseData = await pulseService_1.pulseService.getAudioMetricTimeAnalysis({
                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,
                applicationId: applicationId,
                metricName: metricName,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in metric time analysis controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get metric time analysis data',
                error: error.message,
            });
        }
    },
    async getAiReliability(req, res) {
        try {
            logger_1.default.info('Ai reliability 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 pulseData = await pulseService_1.pulseService.getAiReliabilityScore({
                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,
                applicationId: applicationId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in ai reliability controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get ai reliability data',
                error: error.message,
            });
        }
    },
};
exports.PulseGraphController = PulseGraphController;
//# sourceMappingURL=pulse-graph.js.map