"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PulseSessionController = void 0;
const date_fns_1 = require("date-fns");
const drizzle_orm_1 = require("drizzle-orm");
const logger_1 = __importDefault(require("../../../logger"));
const pulseSessionService_1 = require("../../services/pulseSessionService");
const clickhouse_1 = require("../../../util/clickhouse");
const lodash_1 = __importDefault(require("lodash"));
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const PulseSessionController = {
    async getSessions(req, res) {
        try {
            logger_1.default.info('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 { 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 pulseSessionService = new pulseSessionService_1.PulseSessionService();
            const sessions = await pulseSessionService.getSessions({
                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,
                applicationIds,
            });
            res.json({
                success: true,
                data: sessions,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get sessions controller: ${error}`);
            res.status(500).json({
                success: false,
                message: 'Failed to get sessions',
                error: error.message,
            });
        }
    },
    async getSessionById(req, res) {
        try {
            logger_1.default.info('Session by id endpoint called');
            const { sessionId } = req?.params ?? {};
            const pulseSessionService = new pulseSessionService_1.PulseSessionService();
            const pulseData = await pulseSessionService.getSessionById(sessionId);
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get session by id controller: ${error}`);
            res.status(500).json({
                success: false,
                message: error.message,
                error: error.message,
            });
        }
    },
    async evaluateSession(req, res) {
        try {
            logger_1.default.info('Evaluate session endpoint called');
            const { sessionId } = req?.params ?? {};
            const pulseSessionService = new pulseSessionService_1.PulseSessionService();
            const pulseData = await pulseSessionService.evaluationSessionById({
                id: sessionId,
                projectId: req?.body?.projectId,
                orgId: req?.body?.orgId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in evaluate session controller: ${error}`);
            res.status(500).json({
                success: false,
                message: error.message,
                error: error.message,
            });
        }
    },
    async getSessionEvalResult(req, res) {
        try {
            logger_1.default.info('Get session evaluation result endpoint called');
            const { sessionId } = req?.params ?? {};
            const { orgId } = req?.query ?? {};
            const pulseSessionService = new pulseSessionService_1.PulseSessionService();
            const pulseData = await pulseSessionService.getEvaluation({
                id: sessionId,
                projectId: req?.query?.projectId,
                applicationId: req?.query?.applicationId,
                orgId: orgId,
            });
            res.json({
                success: true,
                data: pulseData,
            });
        }
        catch (error) {
            logger_1.default.error(`Error in get session evaluation result controller: ${error}`);
            res.status(500).json({
                success: false,
                message: error.message,
                error: error.message,
            });
        }
    },
};
exports.PulseSessionController = PulseSessionController;
//# sourceMappingURL=pulse-session.js.map