"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestRunMetricsGraph = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const constants_1 = require("../../../constants");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const workspaceUtils_1 = require("./workspaceUtils");
const getTestRunMetricsGraph = async (params) => {
    try {
        const db = (0, database_1.getDb)();
        const { projectIds, applicationId, start, end, type } = params || {};
        if (!projectIds || projectIds.length === 0) {
            return {
                status: 0,
                message: 'Project IDs are required',
            };
        }
        if (!type || (type !== 'functional' && type !== 'security')) {
            return {
                status: 0,
                message: 'Type must be either "functional" or "security"',
            };
        }
        // Parse dates using shared utility
        const dateStart = (0, workspaceUtils_1.parseStartDate)(start, 7);
        const dateEnd = (0, workspaceUtils_1.parseEndDate)(end);
        // Build date filter conditions for test runs
        const dateConditions = [
            (0, drizzle_orm_1.gte)(tables_1.testRunsTable.createdAt, dateStart),
            (0, drizzle_orm_1.lte)(tables_1.testRunsTable.createdAt, dateEnd),
        ];
        // Build application filter condition
        const applicationConditions = [];
        if (applicationId) {
            applicationConditions.push((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.applicationIds} @> ${JSON.stringify([applicationId])}::jsonb`);
        }
        // Build test run type condition
        const testRunType = type === 'functional' ? constants_1.TEST_RUN_TYPE.EVAL : constants_1.TEST_RUN_TYPE.SECURITY;
        // Fetch test runs in date range
        const testRunsWhereConditions = [
            (0, drizzle_orm_1.inArray)(tables_1.testRunsTable.projectId, projectIds),
            (0, drizzle_orm_1.eq)(tables_1.testRunsTable.status, constants_1.TEST_RUN_STATUS.COMPLETED),
            (0, drizzle_orm_1.eq)(tables_1.testRunsTable.type, testRunType),
            ...dateConditions,
            ...applicationConditions,
        ];
        const testRuns = await db
            .select({
            id: tables_1.testRunsTable.id,
            createdAt: tables_1.testRunsTable.createdAt,
        })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.and)(...testRunsWhereConditions));
        if (testRuns.length === 0) {
            const emptyData = (0, workspaceUtils_1.getDateRangeData)(dateStart, dateEnd);
            return {
                status: 1,
                response: {
                    graphData: emptyData,
                },
            };
        }
        // Get eval IDs for all test runs
        const testRunIds = testRuns.map((tr) => tr.id);
        const testRunToEvals = await db
            .select({
            testRunId: tables_1.testRunsToEvalsTable.testRunId,
            evalId: tables_1.testRunsToEvalsTable.evalId,
        })
            .from(tables_1.testRunsToEvalsTable)
            .where((0, drizzle_orm_1.inArray)(tables_1.testRunsToEvalsTable.testRunId, testRunIds));
        if (testRunToEvals.length === 0) {
            const emptyData = (0, workspaceUtils_1.getDateRangeData)(dateStart, dateEnd);
            return {
                status: 1,
                response: {
                    graphData: emptyData,
                },
            };
        }
        // Create maps for efficient lookups
        const testRunDateMap = new Map();
        for (const tr of testRuns) {
            // Pre-format date string to avoid repeated conversions
            const dateObj = new Date(tr.createdAt);
            const year = dateObj.getUTCFullYear();
            const month = String(dateObj.getUTCMonth() + 1).padStart(2, '0');
            const day = String(dateObj.getUTCDate()).padStart(2, '0');
            testRunDateMap.set(tr.id, `${year}-${month}-${day}`);
        }
        // Create a map of eval ID to test run ID (assuming one-to-one for metrics)
        const evalToTestRunMap = new Map();
        for (const rel of testRunToEvals) {
            evalToTestRunMap.set(rel.evalId, rel.testRunId);
        }
        // Get all eval results
        const allEvalIds = Array.from(new Set(testRunToEvals.map((rel) => rel.evalId)));
        const evalResults = await db
            .select({
            evalId: tables_1.evalResultsTable.evalId,
            success: tables_1.evalResultsTable.success,
        })
            .from(tables_1.evalResultsTable)
            .where((0, drizzle_orm_1.inArray)(tables_1.evalResultsTable.evalId, allEvalIds));
        // Initialize graph data
        const graphData = (0, workspaceUtils_1.getDateRangeData)(dateStart, dateEnd);
        const graphDataMap = new Map();
        for (const dayData of graphData) {
            graphDataMap.set(dayData.date, dayData);
        }
        // Process eval results and aggregate by date
        for (const result of evalResults) {
            const testRunId = evalToTestRunMap.get(result.evalId);
            if (!testRunId) {
                continue;
            }
            const date = testRunDateMap.get(testRunId);
            if (!date) {
                continue;
            }
            const dayData = graphDataMap.get(date);
            if (!dayData) {
                continue;
            }
            // Process component results
            dayData.total += 1;
            if (result?.success) {
                dayData.pass += 1;
            }
            else {
                dayData.fail += 1;
            }
        }
        return {
            status: 1,
            response: {
                graphData,
            },
        };
    }
    catch (error) {
        console.error('Error fetching test run metrics graph:', error);
        return {
            status: 0,
            message: 'Error fetching test run metrics graph',
            error,
        };
    }
};
exports.getTestRunMetricsGraph = getTestRunMetricsGraph;
//# sourceMappingURL=getTestRunMetricsGraph.js.map