"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.canCreatePromptsLibrary = exports.getPromptsLibraryList = 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 get_upgrade_meta_1 = require("../../../util/get-upgrade-meta");
const decimal_js_1 = __importDefault(require("decimal.js"));
const time_1 = require("../../../util/time");
const restriction_message_1 = require("../../constants/restriction.message");
const getPromptsLibraryList = async (req, res) => {
    const db = await (0, database_1.getDb)();
    try {
        const { projectId, search, page, limit, archived_data_required = 'true', orgId } = req.query;
        const includeArchived = archived_data_required === 'true';
        const query = db
            .select({
            id: tables_1.promptsLibraryTable.id,
            name: tables_1.promptsLibraryTable.name,
            createdAt: tables_1.promptsLibraryTable.createdAt,
            projectId: tables_1.promptsLibraryTable.projectId,
            updatedAt: tables_1.promptsLibraryTable.updatedAt,
            is_archived: tables_1.promptsLibraryTable.is_archived,
        })
            .from(tables_1.promptsLibraryTable)
            .orderBy(tables_1.promptsLibraryTable.is_archived, // false first, then true
        (0, drizzle_orm_1.desc)(tables_1.promptsLibraryTable.updatedAt) // within each group, order by updatedAt desc
        );
        const whereConditions = [];
        if (projectId) {
            whereConditions.push((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.projectId, projectId));
        }
        if (search && typeof search === 'string' && search.trim() !== '') {
            whereConditions.push((0, drizzle_orm_1.ilike)(tables_1.promptsLibraryTable.name, `%${search}%`));
        }
        // Add archived filter if needed
        if (!includeArchived) {
            whereConditions.push((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.is_archived, false));
        }
        if (whereConditions.length > 0) {
            query.where((0, drizzle_orm_1.and)(...whereConditions));
        }
        // Apply pagination if both page and limit are provided
        let parsedPage = null;
        let parsedLimit = null;
        if (page !== undefined && limit !== undefined) {
            parsedPage = Number(page);
            parsedLimit = Number(limit);
            if (!Number.isNaN(parsedPage) &&
                !Number.isNaN(parsedLimit) &&
                parsedPage > 0 &&
                parsedLimit > 0) {
                const offset = (parsedPage - 1) * parsedLimit;
                query.limit(parsedLimit).offset(offset);
            }
            else {
                parsedPage = null;
                parsedLimit = null;
            }
        }
        const libraries = await query;
        // Get all prompts for each library
        for (const library of libraries) {
            const promptRelations = await db
                .select({ promptId: tables_1.promptsLibraryPromptsTable.promptId })
                .from(tables_1.promptsLibraryPromptsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.promptsLibraryPromptsTable.libraryId, library.id));
            const promptIds = promptRelations?.map((rel) => rel.promptId);
            library.totalPrompts = promptIds.length;
            const testRuns = await db
                .select({ id: tables_1.testRunsTable.id })
                .from(tables_1.testRunsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.testRunsTable.libraryId, library.id));
            library.totalTestRuns = testRuns.length;
            let prompts = [];
            if (promptIds.length > 0) {
                prompts = await db
                    .select({ id: tables_1.promptsTable.id, tests: tables_1.promptsTable.tests })
                    .from(tables_1.promptsTable)
                    .where((0, drizzle_orm_1.or)(...promptIds.map((id) => (0, drizzle_orm_1.eq)(tables_1.promptsTable.id, id))));
            }
            library.totalTestCases = prompts?.reduce((sum, prompt) => sum + (prompt.tests?.length || 0), 0);
        }
        logger_1.default.info(`Loaded ${libraries?.length} prompt libraries`);
        const { upgradeMetadata, isEnterprise, restrictionsData, wallet, thresholds, globalBanner, } = await (0, get_upgrade_meta_1.getUpgradeMetaByOrgId)(orgId);
        if (!isEnterprise && restrictionsData?.prompt_library > 0) {
            const whereConditions = (0, time_1.createTimespanWhereConditions)({
                table: tables_1.promptsLibraryTable,
                timeColumn: 'createdAt',
                orgId: orgId,
                timespan: restrictionsData?.prompt_library_timespan || 'lifetime',
            });
            const count = await db
                .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
                .from(tables_1.promptsLibraryTable)
                .where(whereConditions)
                .then((result) => Number(result[0]?.count));
            if (count != 0
                && new decimal_js_1.default(count).gte(restrictionsData?.prompt_library ?? 0)) {
                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 ?? '';
            }
        }
        // If paginated request, also return pagination info and total count
        if (parsedPage !== null && parsedLimit !== null) {
            const countQuery = db.select({ count: (0, drizzle_orm_1.sql) `count(*)` }).from(tables_1.promptsLibraryTable);
            if (whereConditions.length > 0) {
                countQuery.where((0, drizzle_orm_1.and)(...whereConditions));
            }
            const total = await countQuery.then((rows) => Number(rows?.[0]?.count ?? 0));
            res.json({
                libraries,
                pagination: {
                    total,
                    page: parsedPage,
                    limit: parsedLimit,
                    totalPages: parsedLimit > 0 ? Math.ceil(total / parsedLimit) : 0,
                },
                upgradeMetadata,
                globalBanner,
            });
            return;
        }
        res.json({ libraries, upgradeMetadata });
    }
    catch (error) {
        logger_1.default.error(`Error fetching prompt libraries: ${error}`);
        res.status(500).json({ error: 'Failed to fetch prompt libraries' });
    }
};
exports.getPromptsLibraryList = getPromptsLibraryList;
const canCreatePromptsLibrary = async (req, res) => {
    try {
        const { orgId } = req.query;
        const { isEnterprise, restrictionsData, upgradeMetadata, globalBanner, wallet, thresholds, } = await (0, get_upgrade_meta_1.getUpgradeMetaByOrgId)(orgId);
        const db = await (0, database_1.getDb)();
        if (!isEnterprise && restrictionsData?.prompt_library > 0) {
            const whereConditions = (0, time_1.createTimespanWhereConditions)({
                table: tables_1.promptsLibraryTable,
                timeColumn: 'createdAt',
                orgId: orgId,
                timespan: restrictionsData?.prompt_library_timespan || 'lifetime',
            });
            const count = await db
                .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
                .from(tables_1.promptsLibraryTable)
                .where(whereConditions)
                .then((result) => Number(result[0]?.count));
            if (count != 0
                && new decimal_js_1.default(count).gte(restrictionsData?.prompt_library ?? 0)) {
                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 ?? '';
            }
        }
        if (!isEnterprise && new decimal_js_1.default(wallet?.credits ?? 0).lte(0)) {
            upgradeMetadata.topUpRequired = true;
            upgradeMetadata.upgradeRequired = false;
            upgradeMetadata.upgradeTitle = restriction_message_1.RESTRICTION_MESSAGE.lowCredits.title;
            upgradeMetadata.upgradeMessage = restriction_message_1.RESTRICTION_MESSAGE.lowCredits.message;
            upgradeMetadata.currentPlan = restrictionsData?.currentPlan ?? '';
            upgradeMetadata.currentPlanId = restrictionsData?.currentPlanId ?? '';
            globalBanner.show = true;
            globalBanner.data.content = `You're low on TRU CREDITS`;
            globalBanner.data.type = 'credits';
            globalBanner.data.action = 'Add TRU CREDITS';
            globalBanner.data.actionType = 'credits';
            globalBanner.data.actionContent = `to continue evaluating your application`;
        }
        if (!isEnterprise) {
            const isLowOnBalance = new decimal_js_1.default(wallet?.credits ?? 0).lte(new decimal_js_1.default(thresholds?.walletNotificationThreshold ?? 0));
            if (isLowOnBalance) {
                globalBanner.show = true;
                globalBanner.data.content = `You're low on TRU CREDITS`;
                globalBanner.data.type = 'credits';
                globalBanner.data.action = 'Add TRU CREDITS';
                globalBanner.data.actionType = 'credits';
                globalBanner.data.actionContent = `to continue evaluating your application`;
            }
        }
        res.json({
            upgradeMetadata,
            globalBanner,
        });
    }
    catch (error) {
        logger_1.default.error(`Error checking if can create prompts library: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to check if can create prompts library',
        });
    }
};
exports.canCreatePromptsLibrary = canCreatePromptsLibrary;
//# sourceMappingURL=get-prompts-library-list.js.map