"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDatasetTestRuns = 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 get_result_list_1 = require("../test-run/get-result-list");
const getDatasetTestRuns = async (req, res) => {
    try {
        const db = await (0, database_1.getDb)();
        const { projectId, page = '1', limit = '10' } = req.query;
        const { id } = req.params;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        const whereCondition = (0, drizzle_orm_1.sql) `${tables_1.testRunsToDatasetsTable.datasetId} = ${id}`;
        const totalCount = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.testRunsToDatasetsTable)
            .where(whereCondition);
        const testRunsToDatasets = await db
            .select({
            testRunId: tables_1.testRunsToDatasetsTable.testRunId,
        })
            .from(tables_1.testRunsToDatasetsTable)
            .where(whereCondition)
            .limit(parsedLimit)
            .offset(offset);
        const testRunIds = testRunsToDatasets.map((r) => r.testRunId);
        const conditions = [(0, drizzle_orm_1.eq)(tables_1.testRunsTable.projectId, projectId)];
        conditions.push((0, drizzle_orm_1.inArray)(tables_1.testRunsTable.id, testRunIds));
        const testRuns = await 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))
            .orderBy((0, drizzle_orm_1.desc)(tables_1.testRunsTable.createdAt));
        // Step 2: fetch all evalResults for these testRuns
        const runIds = testRuns.map((r) => r.id);
        const evalResults = await db
            .select({
            testRunId: tables_1.testRunsToEvalsTable.testRunId,
            evalResultId: tables_1.evalResultsTable.id,
            gradingResult: tables_1.evalResultsTable.gradingResult,
        })
            .from(tables_1.testRunsToEvalsTable)
            .innerJoin(tables_1.evalResultsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.evalId, tables_1.evalResultsTable.evalId))
            .where((0, drizzle_orm_1.inArray)(tables_1.testRunsToEvalsTable.testRunId, runIds));
        // Step 3: group evalResultIds by testRun
        const grouped = {};
        for (const row of evalResults) {
            if (!grouped[row.testRunId]) {
                grouped[row.testRunId] = [];
            }
            grouped[row.testRunId].push(row);
        }
        const applicationIds = [...new Set(testRuns?.flatMap((tr) => tr.applicationIds || []))];
        let applications = [];
        if (applicationIds.length > 0) {
            const appLiteral = drizzle_orm_1.sql.raw(`ARRAY[${applicationIds.map((id) => `'${id}'`).join(',')}]::uuid[]`);
            applications = await db
                .select({
                id: tables_1.applicationsTable.id,
                name: tables_1.applicationsTable.name,
            })
                .from(tables_1.applicationsTable)
                .where((0, drizzle_orm_1.sql) `${tables_1.applicationsTable.id}::uuid = ANY(${appLiteral})`);
        }
        const libraryIds = testRuns.map((tr) => tr.libraryId).filter((id) => id !== null);
        let libraries = [];
        if (libraryIds.length > 0) {
            const libraryLiteral = drizzle_orm_1.sql.raw(`ARRAY[${libraryIds.map((id) => `'${id}'`).join(',')}]::uuid[]`);
            libraries = await db
                .select({
                id: tables_1.promptsLibraryTable.id,
                name: tables_1.promptsLibraryTable.name,
            })
                .from(tables_1.promptsLibraryTable)
                .where((0, drizzle_orm_1.sql) `${tables_1.promptsLibraryTable.id}::uuid = ANY(${libraryLiteral})`);
        }
        // Create lookup maps
        const applicationMap = new Map(applications?.map((app) => [app?.id, app?.name]));
        const libraryMap = new Map(libraries?.map((lib) => [lib?.id, lib?.name]));
        // Format the response
        const formattedTestRuns = testRuns.map((tr) => ({
            id: tr.id,
            createdAt: tr.createdAt,
            status: tr.status,
            applications: tr.applicationIds?.map((id) => applicationMap.get(id) || 'Unknown Application'),
            promptLibrary: tr.libraryId ? libraryMap.get(tr.libraryId) || 'Unknown Library' : null,
            stats: (() => {
                const TestRunEvalResults = grouped[tr.id] || [];
                return (0, get_result_list_1.CalulateTestRunTotalStats)(TestRunEvalResults);
            })(),
        }));
        const result = {
            data: formattedTestRuns,
            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 list: ${error.message}`);
        res.status(500).json({
            success: false,
            message: error.message || 'Failed to fetch test run list',
        });
    }
};
exports.getDatasetTestRuns = getDatasetTestRuns;
//# sourceMappingURL=get-datatset-testruns.js.map