"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestRunSummary = 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 getTestRunSummary = async (req, res) => {
    try {
        const { projectId, applicationIds, libraryIds, testRunIds, page = '1', limit = '10', showSecurityTestRuns = 'false', showTestRuns = 'false', securityConfigId = '', } = req.query;
        const db = await (0, database_1.getDb)();
        if (!db || !projectId) {
            throw new Error('Database connection and projectId are required');
        }
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        const conditions = [(0, drizzle_orm_1.eq)(tables_1.testRunsTable.projectId, projectId)];
        // Handle application IDs
        if (applicationIds && typeof applicationIds === 'string') {
            const apps = applicationIds.split(',').map((id) => id.trim());
            const rawArray = drizzle_orm_1.sql.raw(`array[${apps.map((id) => `'${id}'`).join(',')}]`);
            conditions.push((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.applicationIds}::jsonb ?| ${rawArray}`);
        }
        // Handle library IDs
        if (libraryIds && typeof libraryIds === 'string') {
            conditions.push((0, drizzle_orm_1.inArray)(tables_1.testRunsTable.libraryId, libraryIds.split(',')));
        }
        // Handle test run IDs
        if (testRunIds && typeof testRunIds === 'string') {
            conditions.push((0, drizzle_orm_1.inArray)(tables_1.testRunsTable.id, testRunIds.split(',')));
        }
        // Handle showSecurityTestRuns
        if (showSecurityTestRuns === 'true') {
            conditions.push((0, drizzle_orm_1.eq)(tables_1.testRunsTable.type, 'redteam'));
        }
        // Handle showTestRuns
        if (showTestRuns === 'true') {
            conditions.push((0, drizzle_orm_1.eq)(tables_1.testRunsTable.type, 'eval'));
        }
        // Handle securityConfigId - need to join with testRunsToSecurityConfigsTable
        let testRunsQuery;
        if (securityConfigId) {
            // When securityConfigId is provided, join with testRunsToSecurityConfigsTable
            testRunsQuery = db
                .select({
                id: tables_1.testRunsTable.id,
                createdAt: tables_1.testRunsTable.createdAt,
                status: tables_1.testRunsTable.status,
                applicationIds: tables_1.testRunsTable.applicationIds,
                libraryId: tables_1.testRunsTable.libraryId,
            })
                .from(tables_1.testRunsTable)
                .innerJoin(tables_1.testRunsToSecurityConfigsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, tables_1.testRunsToSecurityConfigsTable.testRunId))
                .where((0, drizzle_orm_1.and)(...conditions, (0, drizzle_orm_1.eq)(tables_1.testRunsToSecurityConfigsTable.securityConfigId, securityConfigId)));
        }
        else {
            // When securityConfigId is not provided, use regular query
            testRunsQuery = db
                .select({
                id: tables_1.testRunsTable.id,
                createdAt: tables_1.testRunsTable.createdAt,
                status: tables_1.testRunsTable.status,
                applicationIds: tables_1.testRunsTable.applicationIds,
                libraryId: tables_1.testRunsTable.libraryId,
            })
                .from(tables_1.testRunsTable)
                .where((0, drizzle_orm_1.and)(...conditions));
        }
        // Get total count for pagination
        let totalCountQuery;
        if (securityConfigId) {
            totalCountQuery = db
                .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
                .from(tables_1.testRunsTable)
                .innerJoin(tables_1.testRunsToSecurityConfigsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, tables_1.testRunsToSecurityConfigsTable.testRunId))
                .where((0, drizzle_orm_1.and)(...conditions, (0, drizzle_orm_1.eq)(tables_1.testRunsToSecurityConfigsTable.securityConfigId, securityConfigId)));
        }
        else {
            totalCountQuery = db
                .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
                .from(tables_1.testRunsTable)
                .where((0, drizzle_orm_1.and)(...conditions));
        }
        const totalCount = await totalCountQuery;
        // Get test runs with pagination
        const testRuns = await testRunsQuery
            .orderBy((0, drizzle_orm_1.desc)(tables_1.testRunsTable.createdAt))
            .limit(parsedLimit)
            .offset(offset);
        const totalPrompts = new Set();
        const testRunSummaries = [];
        for (const testRun of testRuns) {
            const testRunEvals = await db
                .select()
                .from(tables_1.testRunsToEvalsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.testRunId, testRun.id));
            const evalIds = testRunEvals.map((rel) => rel.evalId);
            const evalResults = await db
                .select()
                .from(tables_1.evalResultsTable)
                .where((0, drizzle_orm_1.inArray)(tables_1.evalResultsTable.evalId, evalIds));
            const stats = {
                total: 0,
                successes: 0,
                failures: 0,
                errors: 0,
            };
            for (const result of evalResults) {
                if (result?.gradingResult?.componentResults) {
                    result?.gradingResult?.componentResults?.forEach((componentResult) => {
                        if (result?.promptId) {
                            totalPrompts.add(result?.promptId);
                        }
                        stats.total += 1;
                        if (componentResult?.pass) {
                            stats.successes += 1;
                        }
                        else {
                            stats.failures += 1;
                        }
                    });
                }
            }
            // Get application and library names
            let applicationName;
            if (testRun.applicationIds?.length) {
                const appId = testRun.applicationIds[0];
                const app = await db
                    .select({ name: tables_1.applicationsTable.name })
                    .from(tables_1.applicationsTable)
                    .where((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, appId))
                    .limit(1);
                applicationName = app[0]?.name || undefined;
            }
            // Get library name
            let libraryName;
            if (testRun.libraryId) {
                const lib = await db
                    .select({ name: tables_1.promptsLibraryTable.name })
                    .from(tables_1.promptsLibraryTable)
                    .where((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.id, testRun.libraryId))
                    .limit(1);
                libraryName = lib[0]?.name || undefined;
            }
            testRunSummaries.push({
                id: testRun.id,
                createdAt: testRun.createdAt,
                status: testRun.status,
                applicationName,
                libraryName,
                totalStats: stats,
            });
        }
        const result = {
            totalPrompts: totalPrompts.size,
            list: testRunSummaries,
            pagination: {
                total: Number(totalCount[0].count),
                page: parsedPage,
                limit: parsedLimit,
                totalPages: Math.ceil(Number(totalCount[0].count) / parsedLimit),
            },
        };
        res.json({
            success: true,
            data: result,
        });
    }
    catch (error) {
        logger_1.default.error(`Failed to fetch test run summary: ${error.message}`);
        res.status(500).json({
            success: false,
            message: error.message || 'Failed to fetch test run summary',
        });
    }
};
exports.getTestRunSummary = getTestRunSummary;
//# sourceMappingURL=get-result-summary.js.map