"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDatasetDetails = 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 getDatasetDetails = async (req, res) => {
    try {
        const { id } = req.params;
        const { page, limit } = req.query;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        const hasPaginationQuery = page !== undefined &&
            page !== '' &&
            limit !== undefined &&
            limit !== '' &&
            Number.isFinite(parsedPage) &&
            Number.isFinite(parsedLimit) &&
            parsedLimit > 0;
        if (!id) {
            res.status(400).json({ error: 'Dataset ID is required' });
            return;
        }
        const db = await (0, database_1.getDb)();
        // Get dataset details
        const dataset = await db
            .select({
            id: tables_1.trusysDatasetsTable.id,
            name: tables_1.trusysDatasetsTable.name,
            type: tables_1.trusysDatasetsTable.type,
            status: tables_1.trusysDatasetsTable.status,
            fields: tables_1.trusysDatasetsTable.fields,
            createdAt: tables_1.trusysDatasetsTable.createdAt,
            config: tables_1.trusysDatasetsTable.config,
            is_archived: tables_1.trusysDatasetsTable.is_archived,
        })
            .from(tables_1.trusysDatasetsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.id, id))
            .limit(1);
        if (!dataset[0]) {
            res.status(404).json({ error: 'Dataset not found' });
            return;
        }
        const datasetConfig = dataset[0]?.config ?? null;
        const isGenerateOnEvaluation = Boolean(datasetConfig && datasetConfig.generateOnEvaluation === true);
        // Get test run IDs associated with this dataset.
        // For dynamic datasets (generateOnEvaluation), the linkage is recorded per generated dataset record,
        // so we must derive testRunIds from `testRunsToDatasetRecordsTable`.
        const testRuns = isGenerateOnEvaluation
            ? await db
                .select({
                testRunId: tables_1.testRunsToDatasetRecordsTable.testRunId,
            })
                .from(tables_1.testRunsToDatasetRecordsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.testRunsToDatasetRecordsTable.datasetId, id))
                .groupBy(tables_1.testRunsToDatasetRecordsTable.testRunId)
            : await db
                .select({
                testRunId: tables_1.testRunsToDatasetsTable.testRunId,
            })
                .from(tables_1.testRunsToDatasetsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.testRunsToDatasetsTable.datasetId, id));
        const testRunIds = testRuns.map((run) => run.testRunId);
        // Get dataset records from datasetRecordsTable
        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.eq)(tables_1.datasetRecordsTable.datasetId, id))
            .orderBy((0, drizzle_orm_1.asc)(tables_1.datasetRecordsTable.recordIndex))
            .limit(parsedLimit)
            .offset(offset);
        // Convert records to the expected data format with record ID
        const data = datasetRecords.map((record) => ({
            ...record.recordData,
            _recordId: record.id, // Add the record ID for editing/deleting
        })) ?? [];
        const totalRecords = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.datasetRecordsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.datasetRecordsTable.datasetId, id));
        const recordCount = Number(totalRecords[0]?.count ?? 0);
        let promptLibraryName = null;
        const promptLibraryIdRaw = datasetConfig?.promptLibrary;
        const promptLibraryId = typeof promptLibraryIdRaw === 'string'
            ? promptLibraryIdRaw.trim()
            : promptLibraryIdRaw != null && String(promptLibraryIdRaw).trim() !== ''
                ? String(promptLibraryIdRaw).trim()
                : '';
        if (promptLibraryId.length > 0) {
            const [plRow] = await db
                .select({ name: tables_1.promptsLibraryTable.name })
                .from(tables_1.promptsLibraryTable)
                .where((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.id, promptLibraryId))
                .limit(1);
            const n = plRow?.name;
            if (typeof n === 'string' && n.trim()) {
                promptLibraryName = n.trim();
            }
        }
        // Handle pagination for data when page and limit query params are present
        let pagination = null;
        if (hasPaginationQuery) {
            pagination = {
                total: recordCount,
                page: parsedPage,
                limit: parsedLimit,
                totalPages: Math.max(1, Math.ceil(recordCount / parsedLimit)),
            };
        }
        // Combine dataset details with test run IDs and paginated data
        const response = {
            ...dataset[0],
            promptLibraryName,
            data,
            test_runs: testRunIds,
            recordCount,
            ...(pagination && { pagination }),
        };
        res.json({ data: response });
    }
    catch (error) {
        logger_1.default.error(`Error fetching dataset: ${error}`);
        res.status(500).json({ error: 'Failed to fetch dataset' });
    }
};
exports.getDatasetDetails = getDatasetDetails;
//# sourceMappingURL=get-dataset-details.js.map