"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApplicationTestRunsDetails = 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 getApplicationTestRunsDetails = async (req, res) => {
    try {
        const applicationId = req.query.applicationId;
        const page = Number.parseInt(req.query.page, 10) || 1;
        const limit = Number.parseInt(req.query.limit, 10) || 10;
        const offset = (page - 1) * limit;
        if (!applicationId) {
            res.status(400).json({
                success: false,
                message: 'applicationId is required',
            });
            return;
        }
        const db = await (0, database_1.getDb)();
        // Get total count
        const [{ count }] = await db
            .select({ count: (0, drizzle_orm_1.sql) `COUNT(*)` })
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.applicationIds} @> ${JSON.stringify([applicationId])}::jsonb`);
        // Get paginated test runs
        const testRuns = await db
            .select()
            .from(tables_1.testRunsTable)
            .where((0, drizzle_orm_1.sql) `${tables_1.testRunsTable.applicationIds} @> ${JSON.stringify([applicationId])}::jsonb`)
            .leftJoin(tables_1.promptsLibraryTable, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.libraryId, tables_1.promptsLibraryTable.id))
            .orderBy((0, drizzle_orm_1.desc)(tables_1.testRunsTable.createdAt))
            .limit(limit)
            .offset(offset);
        const totalPages = Math.ceil(count / limit);
        logger_1.default.info(`Fetched ${testRuns.length} test runs for application ${applicationId}`);
        res.json({
            success: true,
            data: testRuns,
            pagination: {
                total: count,
                page,
                limit,
                totalPages,
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching application test runs: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch application test runs',
        });
    }
};
exports.getApplicationTestRunsDetails = getApplicationTestRunsDetails;
//# sourceMappingURL=get-application-test-runs-details.js.map