"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPromptsLibrary = 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 constants_1 = require("../../../constants");
const activityLogService_1 = require("../../services/activityLogService");
const createPromptsLibrary = async (req, res) => {
    const db = await (0, database_1.getDb)();
    try {
        const { projectId, name, orgId } = req.body;
        const libraryId = (0, uuid_1.v4)();
        // Check for existing prompts library with same name and projectId
        const existing = await db
            .select()
            .from(tables_1.promptsLibraryTable)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.name, name), (0, drizzle_orm_1.eq)(tables_1.promptsLibraryTable.projectId, projectId)));
        if (existing.length > 0) {
            res.status(400).json({ error: 'Prompts library with this name already exists.' });
            return;
        }
        const [result] = await db
            .insert(tables_1.promptsLibraryTable)
            .values({
            id: libraryId,
            name,
            projectId,
            workspaceId: orgId,
        })
            .returning({
            id: tables_1.promptsLibraryTable.id,
            name: tables_1.promptsLibraryTable.name,
            createdAt: tables_1.promptsLibraryTable.createdAt,
        });
        logger_1.default.info(`Saved 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 [orgName, projectName] = await Promise.all([
                (0, activityLogService_1.fetchOrgName)(token, orgId),
                (0, activityLogService_1.fetchProjectName)(token, orgId, projectId),
            ]);
            await (0, activityLogService_1.logActivity)(token, {
                type: constants_1.ActivityType.CREATE_PROMPT_LIBRARY,
                params: (0, activityLogService_1.buildActivityParams)({
                    prompt_library_name: { value: name, _id: libraryId },
                    user_name: { value: userName, _id: userId },
                    org_name: { value: orgName || orgId, _id: orgId },
                    project_name: { value: projectName || projectId, _id: projectId },
                }),
                project_id: projectId,
                org_id: orgId,
                created_by: userId,
                updated_by: userId,
            });
        }
        catch (activityError) {
            logger_1.default.error(`Error logging activity for create prompts library: ${activityError}`);
        }
        res.json(result);
    }
    catch (error) {
        logger_1.default.error(`Error saving prompt library: ${error}`);
        res.status(500).json({ error: 'Failed to save prompt library' });
    }
};
exports.createPromptsLibrary = createPromptsLibrary;
//# sourceMappingURL=create-prompts-library.js.map