"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchRedteamResultDetails = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const database_1 = require("../../../util/database");
const get_upgrade_meta_1 = require("../../../util/get-upgrade-meta");
const restriction_message_1 = require("../../constants/restriction.message");
const fetchRedteamResultDetails = async (params) => {
    const { db, resultId, orgId, accessKey = null } = params;
    const result = await db
        .select({
        id: tables_1.testRunsTable.id,
        type: tables_1.testRunsTable.type,
        status: tables_1.testRunsTable.status,
        createdAt: tables_1.testRunsTable.createdAt,
        projectId: tables_1.testRunsTable.projectId,
        applicationIds: tables_1.testRunsTable.applicationIds,
        libraryId: tables_1.testRunsTable.libraryId,
        totalTestCase: tables_1.testRunsTable.totalTestCase,
        shareableReportExpiry: tables_1.testRunsTable.shareableReportExpiry,
        shareableReportAccessKey: tables_1.testRunsTable.shareableReportAccessKey,
        evalId: tables_1.testRunsToEvalsTable.evalId,
        // Fetch only the redteam config blob (not the entire eval config)
        redteamConfig: (0, drizzle_orm_1.sql) `${tables_1.evalsTable.config} -> 'redteam'`,
        securityConfigId: tables_1.testRunsToSecurityConfigsTable.securityConfigId,
        securityConfig: tables_1.securityConfigTable.config,
        securityConfigName: tables_1.securityConfigTable.name,
    })
        .from(tables_1.testRunsTable)
        .leftJoin(tables_1.testRunsToEvalsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, tables_1.testRunsToEvalsTable.testRunId))
        .leftJoin(tables_1.evalsTable, (0, drizzle_orm_1.eq)(tables_1.testRunsToEvalsTable.evalId, tables_1.evalsTable.id))
        .leftJoin(tables_1.testRunsToSecurityConfigsTable, (0, drizzle_orm_1.sql) `${tables_1.testRunsTable.id} = ${tables_1.testRunsToSecurityConfigsTable.testRunId}`)
        .leftJoin(tables_1.securityConfigTable, (0, drizzle_orm_1.sql) `${tables_1.testRunsToSecurityConfigsTable.securityConfigId} = ${tables_1.securityConfigTable.id}`)
        .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.id, resultId))
        .limit(1);
    if (!result.length) {
        return null;
    }
    const testRun = result[0];
    if (accessKey) {
        if (testRun?.shareableReportAccessKey !== accessKey) {
            return null;
        }
        if (testRun?.shareableReportExpiry && testRun?.shareableReportExpiry < new Date()) {
            return null;
        }
    }
    // Get application names
    const applications = await db
        .select({
        id: tables_1.applicationsTable.id,
        name: tables_1.applicationsTable.name,
    })
        .from(tables_1.applicationsTable)
        .where((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, testRun.applicationIds[0]));
    const appMap = new Map(applications?.map((app) => [app.id, app.name]));
    let securityResult = {
        id: testRun?.id,
        evalId: testRun?.evalId,
        createdAt: testRun?.createdAt,
        status: testRun?.status,
        securityConfig: testRun?.redteamConfig ?? testRun?.securityConfig,
        totalTestCase: testRun?.totalTestCase,
        securityConfigName: testRun?.securityConfigName,
        applications: (testRun?.applicationIds || []).map((id) => appMap?.get(id) || id),
        shareableReportAccessKey: testRun?.shareableReportAccessKey,
        shareableReportExpiry: testRun?.shareableReportExpiry,
        redteamStats: {
            strategiesCount: testRun?.redteamConfig?.strategies?.length ||
                testRun?.securityConfig?.strategies?.length ||
                0,
            pluginsCount: testRun?.redteamConfig?.plugins?.length || testRun?.securityConfig?.plugins?.length || 0,
        },
    };
    if (testRun?.evalId) {
        const file = await (0, database_1.fetchEvalResultsFileFromDb)(testRun.evalId, {
            excludePromptResponse: true,
        });
        if (!file) {
            logger_1.default.error(`No evaluation resultfound with ID ${testRun?.evalId}`);
            return null;
        }
        const { upgradeMetadata, isStarter, restrictionsData, } = await (0, get_upgrade_meta_1.getUpgradeMetaByOrgId)(orgId);
        if (isStarter) {
            upgradeMetadata.upgradeRequired = true;
            upgradeMetadata.topUpRequired = false;
            upgradeMetadata.upgradeTitle = restriction_message_1.RESTRICTION_MESSAGE.upgrade.title;
            upgradeMetadata.upgradeMessage = restriction_message_1.RESTRICTION_MESSAGE.upgrade.message;
            upgradeMetadata.currentPlan = restrictionsData?.currentPlan ?? '';
            upgradeMetadata.currentPlanId = restrictionsData?.currentPlanId ?? '';
        }
        securityResult = {
            ...securityResult,
            ...file?.result,
            stats: {
                ...file?.result?.results?.stats,
                total: (file?.result?.results?.stats?.successes ?? 0) +
                    (file?.result?.results?.stats?.failures ?? 0) +
                    (file?.result?.results?.stats?.errors ?? 0),
                failures: file?.result?.results?.stats?.failures ?? 0,
            },
            upgradeMetadata,
        };
    }
    return securityResult;
};
exports.fetchRedteamResultDetails = fetchRedteamResultDetails;
//# sourceMappingURL=get-redteam-result-details.js.map