"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.updatePromptsLibrary = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const uuid_1 = require("uuid");
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 time_1 = require("../../../util/time");
const decimal_js_1 = __importDefault(require("decimal.js"));
const restriction_message_1 = require("../../constants/restriction.message");
const callControlPlaneApi_1 = require("../../../util/callContolPlane/callControlPlaneApi");
const constants_1 = require("../../../constants");
const activityLogService_1 = require("../../services/activityLogService");
const updatePromptsLibrary = async (req, res) => {
    const db = await (0, database_1.getDb)();
    try {
        const { libraryId } = req.params;
        const { prompts, name, projectId, orgId, global_metrics } = req.body;
        const promptIds = [];
        const [library] = await db
            .select()
            .from(tables_1.promptsLibraryTable)
            .where((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.id, libraryId))
            .limit(1);
        if (!library) {
            res.status(404).json({ error: 'Prompt library not found' });
            return;
        }
        if (prompts) {
            let hasConversationAI = false;
            for (const promptData of prompts) {
                if (promptData.promptType === 'conversation_ai') {
                    hasConversationAI = true;
                    break;
                }
            }
            if (hasConversationAI) {
                const { isEnterprise, restrictionsData, notifications, 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)) {
                        res.status(400).json({
                            success: false,
                            message: restriction_message_1.ERROR_RESTRICTION_MESSAGE.upgrade.title,
                            showToast: true,
                            toastMetadata: {
                                text: restriction_message_1.ERROR_RESTRICTION_MESSAGE.upgrade.message,
                                type: 'error',
                            },
                        });
                        return;
                    }
                }
                if (!isEnterprise && new decimal_js_1.default(wallet?.credits ?? 0).lte(0)) {
                    if (notifications?.canSendWalletUsageExceeded) {
                        await (0, callControlPlaneApi_1.callControlPlane)(`/trusys-emails/limit-reached`, {
                            method: 'POST',
                            params: {
                                orgId: orgId,
                                type: 'Wallet',
                                currentUsage: wallet?.credits ?? 0,
                            },
                        }, '');
                    }
                    res.status(400).json({
                        success: false,
                        message: restriction_message_1.ERROR_RESTRICTION_MESSAGE.lowCredits.title,
                        showToast: true,
                        toastMetadata: {
                            text: restriction_message_1.ERROR_RESTRICTION_MESSAGE.lowCredits.message,
                            type: 'error',
                        },
                    });
                    return;
                }
                if (!isEnterprise &&
                    new decimal_js_1.default(wallet?.credits ?? 0).lte(thresholds?.walletNotificationThreshold ?? 0) &&
                    notifications?.canSendLowWalletBalance) {
                    await (0, callControlPlaneApi_1.callControlPlane)(`/trusys-emails/limit-reaching`, {
                        method: 'POST',
                        params: {
                            orgId: orgId,
                            type: 'Wallet',
                            currentUsage: wallet?.credits ?? 0,
                        },
                    }, '');
                }
            }
            await db
                .delete(tables_1.promptsLibraryPromptsTable)
                .where((0, drizzle_orm_1.eq)(tables_1.promptsLibraryPromptsTable.libraryId, libraryId));
            for (const promptData of prompts) {
                const promptCommon = {
                    prompt: promptData.prompt,
                    tests: promptData.tests,
                };
                const additionalFields = promptData.promptType === 'conversation_ai'
                    ? {
                        userIntentions: promptData.userIntentions ?? [],
                        userProfiles: promptData.userProfiles ?? [],
                        openingMessage: promptData.openingMessage ?? '',
                        minimumTurns: promptData?.minimumTurns,
                        maximumTurns: promptData?.maximumTurns,
                        chatStopCriteria: promptData.chatStopCriteria ?? '',
                    }
                    : promptData.promptType === 'conversation_builder'
                        ? {
                            conversationFlow: promptData.conversationFlow,
                            turns: promptData.turns,
                            conversationBuilderType: promptData.conversation_builder_type || 'call', // Default to 'call' for backward compatibility
                        }
                        : {};
                if (promptData?.id) {
                    await db
                        .update(tables_1.promptsTable)
                        .set({
                        ...promptCommon,
                        ...additionalFields,
                        workspaceId: orgId,
                    })
                        .where((0, drizzle_orm_1.eq)(tables_1.promptsTable.id, promptData.id));
                    promptIds.push(promptData.id);
                }
                else {
                    const newPromptId = (0, uuid_1.v4)();
                    await db.insert(tables_1.promptsTable).values({
                        id: newPromptId,
                        prompt: promptData.prompt,
                        type: promptData.promptType,
                        tests: promptData.tests,
                        projectId,
                        workspaceId: orgId,
                        ...additionalFields,
                    });
                    promptIds.push(newPromptId);
                }
            }
            for (const promptId of promptIds) {
                await db.insert(tables_1.promptsLibraryPromptsTable).values({
                    libraryId,
                    promptId,
                });
            }
        }
        const updateData = {};
        if (name !== undefined) {
            updateData.name = name;
        }
        if (projectId !== undefined) {
            updateData.projectId = projectId;
        }
        if (orgId !== undefined) {
            updateData.workspaceId = orgId;
        }
        if (global_metrics !== undefined) {
            updateData.globalMetrics = global_metrics;
        }
        const [result] = await db
            .update(tables_1.promptsLibraryTable)
            .set(updateData)
            .where((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.id, libraryId))
            .returning({
            id: tables_1.promptsLibraryTable.id,
            name: tables_1.promptsLibraryTable.name,
            updatedAt: tables_1.promptsLibraryTable.updatedAt,
        });
        logger_1.default.info(`Updated prompt library ${libraryId}`);
        // Log activity
        try {
            const token = req.headers['x-access-token'] || req.headers.authorization;
            const { userId, userName } = (0, activityLogService_1.getUserInfo)(req);
            const finalName = name ?? library.name;
            const finalProjectId = projectId ?? library?.projectId;
            const finalOrgId = orgId ?? library?.workspaceId;
            const [orgName, projectName] = await Promise.all([
                (0, activityLogService_1.fetchOrgName)(token, finalOrgId),
                (0, activityLogService_1.fetchProjectName)(token, finalOrgId, finalProjectId),
            ]);
            await (0, activityLogService_1.logActivity)(token, {
                type: constants_1.ActivityType.UPDATE_PROMPT_LIBRARY,
                params: (0, activityLogService_1.buildActivityParams)({
                    prompt_library_name: { value: finalName, _id: libraryId },
                    user_name: { value: userName, _id: userId },
                    org_name: { value: orgName || finalOrgId, _id: finalOrgId },
                    project_name: { value: projectName || finalProjectId, _id: finalProjectId },
                }),
                project_id: finalProjectId,
                org_id: finalOrgId,
                created_by: userId,
                updated_by: userId,
            });
        }
        catch (activityError) {
            logger_1.default.error(`Error logging activity for update prompts library: ${activityError}`);
        }
        res.json(result);
    }
    catch (error) {
        logger_1.default.error(`Error updating prompt library: ${error}`);
        res.status(500).json({ error: 'Failed to update prompt library' });
    }
};
exports.updatePromptsLibrary = updatePromptsLibrary;
//# sourceMappingURL=update-prompts-library.js.map