"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const callControlPlaneApi_1 = require("../../util/callContolPlane/callControlPlaneApi");
const permissions_1 = require("../../util/config/permissions");
const getWorkspaceDetails_1 = require("../controller/workspace/getWorkspaceDetails");
const getTestRunMetricsGraph_1 = require("../controller/workspace/getTestRunMetricsGraph");
const getTopMetricFailures_1 = require("../controller/workspace/getTopMetricFailures");
const getPulseMetricsGraph_1 = require("../controller/workspace/getPulseMetricsGraph");
const getPulseTopMetricFailures_1 = require("../controller/workspace/getPulseTopMetricFailures");
const getLatestAlertCondition_1 = require("../controller/workspace/getLatestAlertCondition");
const getPulseTracesStats_1 = require("../controller/workspace/getPulseTracesStats");
const getPulseEvalData_1 = require("../controller/workspace/getPulseEvalData");
const getGuardrailsData_1 = require("../controller/workspace/getGuardrailsData");
const getGuardrailsAlerts_1 = require("../controller/workspace/getGuardrailsAlerts");
const permission_1 = require("../middlewares/permission");
const get_upgrade_meta_1 = require("../../util/get-upgrade-meta");
const decimal_js_1 = __importDefault(require("decimal.js"));
const pulseService_1 = require("../services/pulseService");
const restriction_message_1 = require("../constants/restriction.message");
const workSpaceRouter = express_1.default.Router();
// GET /workspace - Get workspace details for given project IDs
workSpaceRouter.get('/', (0, permission_1.hasPermission)(permissions_1.Permission.ORG_READ), async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        // Convert projectIds to array if it's a string
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getWorkspaceDetails_1.getWorkspaceDetails)({ projectIds: projectIdsArray, applicationId, start, end });
        const { restrictionsData, isStarter, usages, globalBanner, isEnterprise, wallet, thresholds, upgradeMetadata } = await (0, get_upgrade_meta_1.getUpgradeMetaByOrgId)(orgId, {
            fetchMetricUsage: true,
        });
        let spansCount = 0;
        if (isStarter) {
            const spansUsage = await pulseService_1.pulseService.getSpansUsage({
                timeLimit: pulseService_1.pulseService.getTimeLimit(restrictionsData?.spans_timespan ?? 'lifetime'),
                orgId: orgId,
            });
            spansCount = spansUsage;
        }
        if (!isEnterprise && new decimal_js_1.default(wallet?.credits ?? 0).lte(thresholds?.walletNotificationThreshold ?? 0)) {
            globalBanner.show = true;
            globalBanner.data.content = `You're low on TRU CREDITS`;
            globalBanner.data.type = 'credits';
            globalBanner.data.action = 'Add TRU CREDITS';
            globalBanner.data.actionType = 'credits';
            globalBanner.data.actionContent = `to continue evaluating your application`;
        }
        if (isStarter && restrictionsData?.spans > 0 && new decimal_js_1.default(spansCount).gte(restrictionsData?.spans ?? 0)) {
            upgradeMetadata.upgradeRequired = true;
            upgradeMetadata.topUpRequired = false;
            upgradeMetadata.upgradeTitle = restriction_message_1.RESTRICTION_MESSAGE.spans.title;
            upgradeMetadata.upgradeMessage = restriction_message_1.RESTRICTION_MESSAGE.spans.message;
            upgradeMetadata.currentPlan = restrictionsData?.currentPlan ?? '';
            upgradeMetadata.currentPlanId = restrictionsData?.currentPlanId ?? '';
            globalBanner.show = true;
            globalBanner.data.content = `You're out of allotted spans with your ${restrictionsData?.currentPlan ?? ''} plan. `;
            globalBanner.data.type = 'upgrade';
            globalBanner.data.action = 'Upgrade Now';
            globalBanner.data.actionType = 'upgrade';
            globalBanner.data.actionContent = `to continue evaluating your application`;
        }
        if (isStarter
            && restrictionsData?.metrics > 0
            && new decimal_js_1.default(usages?.metric ?? 0).gt(0) && new decimal_js_1.default(usages?.metric ?? 0).gte(restrictionsData?.metrics ?? 0)) {
            upgradeMetadata.upgradeRequired = true;
            upgradeMetadata.topUpRequired = false;
            upgradeMetadata.upgradeTitle = restriction_message_1.RESTRICTION_MESSAGE.metrics.title;
            upgradeMetadata.upgradeMessage = restriction_message_1.RESTRICTION_MESSAGE.metrics.message;
            upgradeMetadata.currentPlan = restrictionsData?.currentPlan ?? '';
            upgradeMetadata.currentPlanId = restrictionsData?.currentPlanId ?? '';
            globalBanner.show = true;
            globalBanner.data.content = `You're out of allotted metrics with your ${restrictionsData?.currentPlan ?? ''} plan. `;
            globalBanner.data.type = 'upgrade';
            globalBanner.data.action = 'Upgrade Now';
            globalBanner.data.actionType = 'upgrade';
            globalBanner.data.actionContent = `to continue evaluating your application`;
        }
        if (result.status === 0) {
            res.status(400).json({
                ...result,
                response: {
                    ...(result.response ?? {}),
                    globalBanner,
                    upgradeMetadata,
                }
            });
        }
        res.json({
            ...result,
            response: {
                ...(result.response ?? {}),
                globalBanner,
                upgradeMetadata,
            }
        });
    }
    catch (error) {
        console.error('Error in workspace route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/metrics-graph - Get test case metrics graph data
workSpaceRouter.get('/metrics-graph', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId, type } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        if (!type || (type !== 'functional' && type !== 'security')) {
            res.status(400).json({
                status: 0,
                message: 'Type must be either "functional" or "security"',
            });
            return;
        }
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getTestRunMetricsGraph_1.getTestRunMetricsGraph)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
            type,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in metrics graph route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/top-failures - Get top metric failures
workSpaceRouter.get('/top-failures', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId, type, limit } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        if (!type || (type !== 'functional' && type !== 'security')) {
            res.status(400).json({
                status: 0,
                message: 'Type must be either "functional" or "security"',
            });
            return;
        }
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getTopMetricFailures_1.getTopMetricFailures)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
            type,
            limit: limit ? Number(limit) : 5,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in top failures route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/pulse-metrics-graph - Get pulse metrics graph data
workSpaceRouter.get('/pulse-metrics-graph', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getPulseMetricsGraph_1.getPulseMetricsGraph)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in pulse metrics graph route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/pulse-top-failures - Get pulse top metric failures
workSpaceRouter.get('/pulse-top-failures', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId, limit } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getPulseTopMetricFailures_1.getPulseTopMetricFailures)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
            limit: limit ? Number(limit) : 5,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in pulse top failures route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/latest-alert-condition - Get latest alert condition and total alerts triggered
workSpaceRouter.get('/latest-alert-condition', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getLatestAlertCondition_1.getLatestAlertCondition)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in latest alert condition route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/pulse-traces-stats - Get total traces and total traces evaluated
workSpaceRouter.get('/pulse-traces-stats', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getPulseTracesStats_1.getPulseTracesStats)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in pulse traces stats route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/pulse-eval-data - Get pulse eval count and last 7 days data
workSpaceRouter.get('/pulse-eval-data', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getPulseEvalData_1.getPulseEvalData)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in pulse eval data route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/guardrails-data - Get guardrails data
workSpaceRouter.get('/guardrails-data', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getGuardrailsData_1.getGuardrailsData)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in guardrails data route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
// GET /workspace/guardrails-alerts - Get guardrails alerts
workSpaceRouter.get('/guardrails-alerts', 
/* hasPermission(Permission.ORG_READ), */
async (req, res) => {
    try {
        const { orgId, projectId, start, end, applicationId } = req.query;
        const token = req.headers['x-access-token'] || req.headers.authorization;
        const workSpaceProjectsResponse = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/projectS`, {
            method: 'GET',
            params: {
                page: 1,
                limit: 999,
            },
        }, token);
        const workspaceAllProjectIds = Array.isArray(workSpaceProjectsResponse?.response?.projects)
            ? workSpaceProjectsResponse?.response?.projects?.map((project) => project?._id)
            : [];
        const projectIdsArray = projectId ? [projectId] : workspaceAllProjectIds;
        const result = await (0, getGuardrailsAlerts_1.getGuardrailsAlerts)({
            projectIds: projectIdsArray,
            applicationId,
            start,
            end,
        });
        if (result.status === 0) {
            res.status(400).json(result);
            return;
        }
        res.json(result);
    }
    catch (error) {
        console.error('Error in guardrails alerts route:', error);
        res.status(500).json({
            status: 0,
            message: 'Internal server error',
            error,
        });
    }
});
exports.default = workSpaceRouter;
//# sourceMappingURL=workspace.js.map