"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTestRunDatasetRecords = 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 getTestRunDatasetRecords = async (req, res) => {
    try {
        const db = await (0, database_1.getDb)();
        const { testRunId } = req.params;
        const { datasetId, page = '1', limit = '10' } = req.query;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        if (!testRunId || !datasetId) {
            res.status(400).json({
                success: false,
                message: 'testRunId and datasetId are required',
            });
            return;
        }
        // Build where conditions
        const conditions = [(0, drizzle_orm_1.eq)(tables_1.testRunsToDatasetRecordsTable.testRunId, testRunId)];
        if (datasetId) {
            conditions.push((0, drizzle_orm_1.eq)(tables_1.testRunsToDatasetRecordsTable.datasetId, datasetId));
        }
        // Get total count
        const totalCountResult = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.testRunsToDatasetRecordsTable)
            .where((0, drizzle_orm_1.and)(...conditions));
        const totalCount = Number(totalCountResult[0]?.count ?? 0);
        // Fetch dataset records linked to the test run
        const testRunDatasetRecords = await db
            .select({
            datasetRecordId: tables_1.testRunsToDatasetRecordsTable.datasetRecordId,
            datasetId: tables_1.testRunsToDatasetRecordsTable.datasetId,
        })
            .from(tables_1.testRunsToDatasetRecordsTable)
            .where((0, drizzle_orm_1.and)(...conditions))
            .limit(parsedLimit)
            .offset(offset);
        const datasetRecordIds = testRunDatasetRecords.map((r) => r.datasetRecordId);
        if (datasetRecordIds.length === 0) {
            res.json({
                success: true,
                data: {
                    records: [],
                    pagination: {
                        total: totalCount,
                        page: parsedPage,
                        limit: parsedLimit,
                        totalPages: Math.ceil(totalCount / parsedLimit),
                    },
                },
            });
            return;
        }
        // Fetch the actual dataset records using inArray
        const datasetRecords = await db
            .select({
            id: tables_1.datasetRecordsTable.id,
            recordData: tables_1.datasetRecordsTable.recordData,
            recordIndex: tables_1.datasetRecordsTable.recordIndex,
        })
            .from(tables_1.datasetRecordsTable)
            .where((0, drizzle_orm_1.inArray)(tables_1.datasetRecordsTable.id, datasetRecordIds))
            .orderBy((0, drizzle_orm_1.asc)(tables_1.datasetRecordsTable.recordIndex));
        // Convert records to the expected data format
        const records = datasetRecords.map((record) => ({
            ...record.recordData,
            _recordId: record.id,
            recordIndex: record.recordIndex,
        }));
        const result = {
            records,
            pagination: {
                total: totalCount,
                page: parsedPage,
                limit: parsedLimit,
                totalPages: Math.ceil(totalCount / parsedLimit),
            },
        };
        res.json({
            success: true,
            data: result,
        });
    }
    catch (error) {
        logger_1.default.error(`Failed to fetch test run dataset records: ${error.message}`);
        res.status(500).json({
            success: false,
            message: error.message || 'Failed to fetch test run dataset records',
        });
    }
};
exports.getTestRunDatasetRecords = getTestRunDatasetRecords;
//# sourceMappingURL=get-test-run-dataset-records.js.map