"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PulseCronController = void 0;
const date_fns_1 = require("date-fns");
const logger_1 = __importDefault(require("../../../logger"));
const pulseAlertCheckCronService_1 = require("../../services/pulseAlertCheckCronService");
const pulseCronService_1 = require("../../services/pulseCronService");
const pulseMonitoringService_1 = require("../../services/pulseMonitoringService");
const callControlPlaneApi_1 = require("../../../util/callContolPlane/callControlPlaneApi");
const decimal_js_1 = __importDefault(require("decimal.js"));
const PulseCronController = {
    async evaluateTraces(req, res) {
        try {
            const { applicationIds, startTime, endTime } = req?.body ?? {};
            const correlationId = res.locals.correlationId;
            const finalStartTime = startTime ?? (0, date_fns_1.format)((0, date_fns_1.sub)(new Date(), { hours: 1 }), 'yyyy-MM-dd HH:mm:ss');
            const finalEndTime = endTime ?? (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd HH:mm:ss');
            // Return response immediately
            res.status(200).json({ message: `Cron job started at ${finalStartTime} to ${finalEndTime}` });
            // Run the actual processing in the background
            setImmediate(async () => {
                try {
                    const applicationLimit = 100;
                    let applicationOffset = 1;
                    // Get initial batch of applications with monitoring
                    let applicationsWithMonitoring = await pulseMonitoringService_1.pulseMonitoringService.getApplicationsWithMonitoring({
                        limit: applicationLimit,
                        page: applicationOffset,
                        applicationIds,
                    });
                    let orgIds = new Set(applicationsWithMonitoring?.map((application) => application?.workspaceId) ?? []);
                    const orgRestrictions = await (0, callControlPlaneApi_1.callControlPlane)(`/trusys/billing-plans-in-bulk`, {
                        method: 'POST',
                        params: {
                            orgIds: Array.from(orgIds).filter((orgId) => orgId !== null && orgId !== undefined && orgId !== '' && orgId !== 'null' && orgId !== 'undefined'),
                        },
                    }, '');
                    const skipMap = new Map();
                    const renewalNotificationMap = new Map();
                    const usageNotificationMap = new Map();
                    const exhaustedNotificationMap = new Map();
                    let restrictionsData = orgRestrictions?.response ?? {};
                    applicationsWithMonitoring = applicationsWithMonitoring.filter(async (application) => {
                        const orgId = application?.workspaceId;
                        const restrictions = restrictionsData[orgId] ?? {};
                        // wallet negative balance check
                        // should not check for enterprise
                        if (restrictions?.isEnterprise === false &&
                            new decimal_js_1.default(restrictions?.wallet?.credits ?? 0).lte(0)
                            && !exhaustedNotificationMap.get(orgId)?.wallet) {
                            exhaustedNotificationMap.set(orgId, {
                                spans: exhaustedNotificationMap.get(orgId)?.spans ?? false,
                                metric: exhaustedNotificationMap.get(orgId)?.metric ?? false,
                                wallet: true
                            });
                            skipMap.set(orgId, true);
                            await (0, callControlPlaneApi_1.callControlPlane)(`/trusys-emails/limit-reached`, {
                                method: 'POST',
                                params: {
                                    orgId,
                                    type: 'Wallet',
                                    currentUsage: restrictions?.wallet?.credits ?? 0,
                                },
                            }, '');
                            return false;
                        }
                        return true;
                    });
                    // Loop through applications with monitoring
                    while (applicationsWithMonitoring?.length > 0) {
                        console.log(`Starting cron job with correlation ID: ${JSON.stringify({
                            correlationId,
                            finalStartTime,
                            finalEndTime,
                            limit: applicationLimit,
                            offset: applicationOffset,
                            applicationIds,
                            actualApplications: applicationsWithMonitoring?.map((application) => application.applicationId),
                        })}`);
                        for (const application of applicationsWithMonitoring) {
                            // Evaluate traces for each application
                            try {
                                await pulseCronService_1.pulseCronService.evaluateApplicationTraces({
                                    startTime: finalStartTime,
                                    endTime: finalEndTime,
                                    applicationId: application.applicationId,
                                    monitoringConfig: application,
                                    application: application.application,
                                    correlationId,
                                    skipMap,
                                    orgRestrictions: restrictionsData?.[application?.workspaceId] ?? {},
                                    orgId: application?.workspaceId,
                                    renewalNotificationMap,
                                    usageNotificationMap,
                                    exhaustedNotificationMap,
                                });
                            }
                            catch (error) {
                                logger_1.default.error(`Error in pulse cron controller: ${application.applicationId} - ${error}`);
                            }
                        }
                        // Increment application offset
                        applicationOffset = applicationOffset + 1;
                        // Get next batch of applications with monitoring
                        applicationsWithMonitoring = await pulseMonitoringService_1.pulseMonitoringService.getApplicationsWithMonitoring({
                            limit: applicationLimit,
                            page: applicationOffset,
                            applicationIds,
                        });
                        orgIds = new Set(applicationsWithMonitoring?.map((application) => application?.workspaceId) ?? []);
                        const orgRestrictions = await (0, callControlPlaneApi_1.callControlPlane)(`/trusys/billing-plans-in-bulk`, {
                            method: 'POST',
                            params: {
                                orgIds: Array.from(orgIds).filter((orgId) => orgId !== null && orgId !== undefined && orgId !== '' && orgId !== 'null' && orgId !== 'undefined'),
                            },
                        }, '');
                        restrictionsData = orgRestrictions?.response ?? {};
                        // just check for wallet balance at this level
                        applicationsWithMonitoring = applicationsWithMonitoring.filter((application) => {
                            const orgId = application?.workspaceId;
                            const restrictions = restrictionsData[orgId] ?? {};
                            if (restrictions?.isEnterprise === false &&
                                new decimal_js_1.default(restrictions?.wallet?.credits ?? 0).lte(0)) {
                                return false;
                            }
                            return true;
                        });
                    }
                }
                catch (error) {
                    logger_1.default.error(`Error in pulse cron controller background processing: ${error}`);
                }
            });
        }
        catch (error) {
            logger_1.default.error(`Error in pulse cron controller: ${error}`);
            // Only send error response if headers haven't been sent yet
            if (!res.headersSent) {
                res.status(200).json({ message: 'Error starting cron job' });
            }
        }
    },
    async evaluateSessions(req, res) {
        try {
            const { applicationIds, startTime, endTime } = req?.body ?? {};
            const correlationId = res.locals.correlationId;
            const finalStartTime = startTime ?? (0, date_fns_1.format)((0, date_fns_1.sub)(new Date(), { hours: 1 }), 'yyyy-MM-dd HH:mm:ss');
            const finalEndTime = endTime ?? (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd HH:mm:ss');
            // Return response immediately
            res.status(200).json({ message: `Sessions Cron job started at ${finalStartTime} to ${finalEndTime}` });
            // Run the actual processing in the background
            setImmediate(async () => {
                try {
                    const applicationLimit = 100;
                    let applicationOffset = 1;
                    // Get initial batch of applications with monitoring
                    let applicationsWithMonitoring = await pulseMonitoringService_1.pulseMonitoringService.getApplicationsWithMonitoring({
                        limit: applicationLimit,
                        page: applicationOffset,
                        applicationIds,
                    });
                    let orgIds = new Set(applicationsWithMonitoring?.map((application) => application?.workspaceId) ?? []);
                    const orgRestrictions = await (0, callControlPlaneApi_1.callControlPlane)(`/trusys/billing-plans-in-bulk`, {
                        method: 'POST',
                        params: {
                            orgIds: Array.from(orgIds).filter((orgId) => orgId !== null && orgId !== undefined && orgId !== '' && orgId !== 'null' && orgId !== 'undefined'),
                        },
                    }, '');
                    const skipMap = new Map();
                    const renewalNotificationMap = new Map();
                    const usageNotificationMap = new Map();
                    const exhaustedNotificationMap = new Map();
                    let restrictionsData = orgRestrictions?.response ?? {};
                    // just check for wallet balance at this level
                    applicationsWithMonitoring = applicationsWithMonitoring.filter(async (application) => {
                        const orgId = application?.workspaceId;
                        const restrictions = restrictionsData[orgId] ?? {};
                        if (restrictions?.isEnterprise === false &&
                            new decimal_js_1.default(restrictions?.wallet?.credits ?? 0).lte(0)
                            && !exhaustedNotificationMap.get(orgId)?.wallet) {
                            exhaustedNotificationMap.set(orgId, {
                                spans: exhaustedNotificationMap.get(orgId)?.spans ?? false,
                                metric: exhaustedNotificationMap.get(orgId)?.metric ?? false,
                                wallet: true
                            });
                            skipMap.set(orgId, true);
                            await (0, callControlPlaneApi_1.callControlPlane)(`/trusys-emails/limit-reached`, {
                                method: 'POST',
                                params: {
                                    orgId,
                                    type: 'Wallet',
                                    currentUsage: restrictions?.wallet?.credits ?? 0,
                                },
                            }, '');
                            return false;
                        }
                        return true;
                    });
                    // Loop through applications with monitoring
                    while (applicationsWithMonitoring?.length > 0) {
                        console.log(`Starting sessions cron job with correlation ID: ${JSON.stringify({
                            correlationId,
                            finalStartTime,
                            finalEndTime,
                            limit: applicationLimit,
                            offset: applicationOffset,
                            applicationIds,
                            actualApplications: applicationsWithMonitoring?.map((application) => application.applicationId),
                        })}`);
                        for (const application of applicationsWithMonitoring) {
                            // Evaluate traces for each application
                            try {
                                await pulseCronService_1.pulseCronService.evaluateApplicationSessions({
                                    startTime: finalStartTime,
                                    endTime: finalEndTime,
                                    applicationId: application.applicationId,
                                    monitoringConfig: application,
                                    application: application.application,
                                    correlationId,
                                    skipMap,
                                    orgRestrictions: restrictionsData?.[application?.workspaceId] ?? {},
                                    orgId: application?.workspaceId,
                                    renewalNotificationMap,
                                    usageNotificationMap,
                                    exhaustedNotificationMap,
                                });
                            }
                            catch (error) {
                                logger_1.default.error(`Error in pulse cron controller: ${application.applicationId} - ${error}`);
                            }
                        }
                        // Increment application offset
                        applicationOffset = applicationOffset + 1;
                        // Get next batch of applications with monitoring
                        applicationsWithMonitoring = await pulseMonitoringService_1.pulseMonitoringService.getApplicationsWithMonitoring({
                            limit: applicationLimit,
                            page: applicationOffset,
                            applicationIds,
                        });
                        orgIds = new Set(applicationsWithMonitoring?.map((application) => application?.workspaceId) ?? []);
                        const orgRestrictions = await (0, callControlPlaneApi_1.callControlPlane)(`/trusys/billing-plans-in-bulk`, {
                            method: 'POST',
                            params: {
                                orgIds: Array.from(orgIds).filter((orgId) => orgId !== null && orgId !== undefined && orgId !== '' && orgId !== 'null' && orgId !== 'undefined'),
                            },
                        }, '');
                        restrictionsData = orgRestrictions?.response ?? {};
                        // just check for wallet balance at this level
                        applicationsWithMonitoring = applicationsWithMonitoring.filter((application) => {
                            const orgId = application?.workspaceId;
                            const restrictions = restrictionsData[orgId] ?? {};
                            if (new decimal_js_1.default(restrictions?.wallet?.credits ?? 0).lte(0)) {
                                return false;
                            }
                            return true;
                        });
                    }
                }
                catch (error) {
                    logger_1.default.error(`Error in pulse sessions cron controller background processing: ${error}`);
                }
            });
        }
        catch (error) {
            logger_1.default.error(`Error in pulse sessions cron controller: ${error}`);
            // Only send error response if headers haven't been sent yet
            if (!res.headersSent) {
                res.status(200).json({ message: 'Error starting sessions cron job' });
            }
        }
    },
    async checkAlerts(req, res) {
        try {
            logger_1.default.info('Checking alerts for all active monitoring configurations');
            // Return response immediately
            res.json({
                success: true,
                message: 'Alert check job started',
            });
            // Run the actual processing in the background
            setImmediate(async () => {
                try {
                    const _result = await pulseAlertCheckCronService_1.pulseAlertCheckCronService.checkAllAlerts();
                    logger_1.default.info('Alert check job completed successfully');
                }
                catch (error) {
                    logger_1.default.error(`Error in check alerts controller background processing: ${error}`);
                }
            });
        }
        catch (error) {
            logger_1.default.error(`Error in check alerts controller: ${error}`);
            // Only send error response if headers haven't been sent yet
            if (!res.headersSent) {
                res.status(200).json({
                    success: false,
                    message: error.message,
                    error: error.message,
                });
            }
        }
    },
    async observationDashboardPopulate(req, res) {
        try {
            const { applicationIds, startTime, endTime, traceIds = [] } = req?.body ?? {};
            const correlationId = res.locals.correlationId;
            const finalStartTime = startTime ?? (0, date_fns_1.format)((0, date_fns_1.sub)(new Date(), { hours: 1 }), 'yyyy-MM-dd HH:mm:ss');
            const finalEndTime = endTime ?? (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd HH:mm:ss');
            // Return response immediately
            res.status(200).json({ message: `Cron job for Observation Population started at ${finalStartTime} to ${finalEndTime}` });
            // Run the actual processing in the background
            setImmediate(async () => {
                try {
                    const applicationLimit = 100;
                    let applicationOffset = 1;
                    // Get initial batch of applications with monitoring
                    let applicationsWithMonitoring = await pulseMonitoringService_1.pulseMonitoringService.getApplicationsWithMonitoring({
                        limit: applicationLimit,
                        page: applicationOffset,
                        applicationIds,
                    });
                    // Loop through applications with monitoring
                    while (applicationsWithMonitoring?.length > 0) {
                        console.log(`Starting observation dashboard populate cron job with correlation ID: ${JSON.stringify({
                            correlationId,
                            finalStartTime,
                            finalEndTime,
                            limit: applicationLimit,
                            offset: applicationOffset,
                            applicationIds,
                            actualApplications: applicationsWithMonitoring?.map((application) => application.applicationId),
                            traceIds,
                        })}`);
                        for (const application of applicationsWithMonitoring) {
                            // Evaluate traces for each application
                            try {
                                await pulseCronService_1.pulseCronService.observationDashboardPopulate({
                                    startTime: finalStartTime,
                                    endTime: finalEndTime,
                                    applicationId: application.applicationId,
                                    monitoringConfig: application,
                                    application: application.application,
                                    correlationId,
                                    traceIds,
                                });
                            }
                            catch (error) {
                                logger_1.default.error(`Error in observation dashboard populate cron job: ${application.applicationId} - ${error}`);
                            }
                        }
                        // Increment application offset
                        applicationOffset = applicationOffset + 1;
                        // Get next batch of applications with monitoring
                        applicationsWithMonitoring = await pulseMonitoringService_1.pulseMonitoringService.getApplicationsWithMonitoring({
                            limit: applicationLimit,
                            page: applicationOffset,
                            applicationIds,
                        });
                    }
                }
                catch (error) {
                    logger_1.default.error(`Error in observation dashboard populate cron job background processing: ${error}`);
                }
            });
        }
        catch (error) {
            logger_1.default.error(`Error in observation dashboard populate cron job: ${error}`);
            // Only send error response if headers haven't been sent yet
            if (!res.headersSent) {
                res.status(200).json({ message: 'Error starting observation dashboard populate cron job' });
            }
        }
    },
};
exports.PulseCronController = PulseCronController;
//# sourceMappingURL=pulse-cron.js.map