"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getComparableTestRuns = 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 getComparableTestRuns = async (req, res) => {
    try {
        const { resultId } = req.params;
        const { projectId, page = 1, limit = 10 } = req.query;
        const db = await (0, database_1.getDb)();
        const pageNum = Number.parseInt(page, 10);
        const limitNum = Number.parseInt(limit, 10);
        const offset = (pageNum - 1) * limitNum;
        // Get the current test run details
        const currentTestRun = await db
            .select({
            id: tables_1.testRunsTable.id,
            libraryId: tables_1.testRunsTable.libraryId,
            projectId: tables_1.testRunsTable.projectId,
        })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, resultId))
            .limit(1);
        if (!currentTestRun.length) {
            res.status(404).json({
                success: false,
                message: 'Test run not found',
            });
            return;
        }
        const { libraryId } = currentTestRun[0];
        // Get datasets linked to current test run
        const currentTestRunDatasets = await db
            .select({ datasetId: tables_1.testRunsToDatasetsTable.datasetId })
            .from(tables_1.testRunsToDatasetsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.testRunsToDatasetsTable.testRunId, resultId));
        const currentDatasetIds = currentTestRunDatasets.map((d) => d.datasetId);
        // Build the main query conditions
        const baseConditions = [
            (0, drizzle_orm_1.eq)(tables_1.testRunsTable.projectId, projectId),
            (0, drizzle_orm_1.ne)(tables_1.testRunsTable.id, resultId),
            (0, drizzle_orm_1.eq)(tables_1.testRunsTable.status, 'completed'),
        ];
        if (libraryId) {
            baseConditions.push((0, drizzle_orm_1.eq)(tables_1.testRunsTable.libraryId, libraryId));
        }
        // Build query based on whether datasets are linked
        let comparableTestRunsQuery;
        let totalCountQuery;
        if (currentDatasetIds.length > 0) {
            // If datasets are linked, filter by same datasets
            const datasetConditions = [
                ...baseConditions,
                (0, drizzle_orm_1.inArray)(tables_1.testRunsToDatasetsTable.datasetId, currentDatasetIds),
            ];
            comparableTestRunsQuery = db
                .select({
                id: tables_1.testRunsTable.id,
                createdAt: tables_1.testRunsTable.createdAt,
                libraryId: tables_1.testRunsTable.libraryId,
                status: tables_1.testRunsTable.status,
            })
                .from(tables_1.testRunsTable)
                .innerJoin(tables_1.testRunsToDatasetsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, tables_1.testRunsToDatasetsTable.testRunId))
                .where((0, drizzle_orm_1.and)(...datasetConditions))
                .orderBy((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.createdAt} DESC`)
                .limit(limitNum)
                .offset(offset);
            totalCountQuery = db
                .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
                .from(tables_1.testRunsTable)
                .innerJoin(tables_1.testRunsToDatasetsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, tables_1.testRunsToDatasetsTable.testRunId))
                .where((0, drizzle_orm_1.and)(...datasetConditions));
        }
        else {
            // If no datasets linked, filter by same library only
            comparableTestRunsQuery = db
                .select({
                id: tables_1.testRunsTable.id,
                createdAt: tables_1.testRunsTable.createdAt,
                libraryId: tables_1.testRunsTable.libraryId,
                status: tables_1.testRunsTable.status,
            })
                .from(tables_1.testRunsTable)
                .where((0, drizzle_orm_1.and)(...baseConditions))
                .orderBy((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.createdAt} DESC`)
                .limit(limitNum)
                .offset(offset);
            totalCountQuery = db
                .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
                .from(tables_1.testRunsTable)
                .where((0, drizzle_orm_1.and)(...baseConditions));
        }
        const [comparableTestRuns, totalCountResult] = await Promise.all([
            comparableTestRunsQuery,
            totalCountQuery,
        ]);
        const totalCount = totalCountResult[0]?.count || 0;
        res.json({
            success: true,
            data: comparableTestRuns,
            pagination: {
                page: pageNum,
                limit: limitNum,
                total: totalCount,
                totalPages: Math.ceil(totalCount / limitNum),
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Failed to fetch comparable test runs: ${error.message}`);
        res.status(500).json({
            success: false,
            message: error.message || 'Failed to fetch comparable test runs',
        });
    }
};
exports.getComparableTestRuns = getComparableTestRuns;
//# sourceMappingURL=get-comparable-test-runs.js.map