"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApplicationDetails = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const lodash_1 = __importDefault(require("lodash"));
const getApplicationDetails = async (req, res) => {
    try {
        const applicationId = req.query.applicationId;
        const projectId = req.query.projectId;
        const name = req.query.name;
        const db = await (0, database_1.getDb)();
        let application;
        if (applicationId) {
            [application] = await db
                .select()
                .from(tables_1.applicationsTable)
                .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, applicationId), (0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId)))
                .limit(1);
        }
        else if (name) {
            [application] = await db
                .select()
                .from(tables_1.applicationsTable)
                .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId), (0, drizzle_orm_1.or)((0, drizzle_orm_1.eq)(tables_1.applicationsTable.name, name), (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, name))))
                .limit(1);
        }
        else {
            res.status(400).json({
                success: false,
                message: 'Either applicationId or name must be provided',
            });
            return;
        }
        if (!application) {
            res.status(404).json({
                success: false,
                message: 'Application not found',
            });
            return;
        }
        const [evalCountResult] = await db
            .select({ count: (0, drizzle_orm_1.sql) `COUNT(*)` })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.applicationIds} @> ${JSON.stringify([application.id])}::jsonb`, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.type, 'eval')));
        const [securityCountResult] = await db
            .select({ count: (0, drizzle_orm_1.sql) `COUNT(*)` })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.applicationIds} @> ${JSON.stringify([application.id])}::jsonb`, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.type, 'redteam')));
        const [pulseEntry] = await db
            .select({
            metrics: tables_1.pulseMonitoringTable.metrics,
            pluginsByCategory: tables_1.pulseMonitoringTable.pluginsByCategory,
            logLocation: tables_1.pulseMonitoringTable.logLocation,
        })
            .from(tables_1.pulseMonitoringTable)
            .where((0, drizzle_orm_1.eq)(tables_1.pulseMonitoringTable.applicationId, application.id));
        const functionalMonitoringEnabled = Array.isArray(pulseEntry?.metrics) && pulseEntry.metrics.length > 0;
        const plugins = pulseEntry?.pluginsByCategory;
        let securityMonitoringEnabled = false;
        if (plugins && typeof plugins === 'object' && !Array.isArray(plugins)) {
            securityMonitoringEnabled = Object.values(plugins).some((value) => Array.isArray(value) && value.length > 0);
        }
        securityMonitoringEnabled = lodash_1.default.isEmpty(pulseEntry) ? false : true;
        const functionalEvaluationCount = evalCountResult?.count || 0;
        const securityEvaluationCount = securityCountResult?.count || 0;
        // Fetch guardrails configuration
        const [guardrailsConfig] = await db
            .select()
            .from(tables_1.applicationGuardrailsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.applicationGuardrailsTable.applicationId, application.id))
            .limit(1);
        logger_1.default.info(`Fetched application ${applicationId || name}`);
        res.json({
            ...application,
            functionalEvaluationCount,
            providerType: application?.provider_type || null,
            securityEvaluationCount,
            functionalMonitoringEnabled,
            securityMonitoringEnabled,
            logLocation: pulseEntry?.logLocation || null,
            enable_guard_rails: guardrailsConfig?.enable_guard_rails || false,
            guardRails: guardrailsConfig
                ? {
                    input_validators: guardrailsConfig.input_validators || [],
                    output_validators: guardrailsConfig.output_validators || [],
                }
                : null,
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching application: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch application',
        });
    }
};
exports.getApplicationDetails = getApplicationDetails;
//# sourceMappingURL=get-application-details.js.map