"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDataset = 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 get_upgrade_meta_1 = require("../../../util/get-upgrade-meta");
const decimal_js_1 = __importDefault(require("decimal.js"));
const callControlPlaneApi_1 = require("../../../util/callContolPlane/callControlPlaneApi");
const restriction_message_1 = require("../../constants/restriction.message");
const logger_1 = __importDefault(require("../../../logger"));
const constants_1 = require("../../../constants");
const activityLogService_1 = require("../../services/activityLogService");
const createDataset = async (req, res) => {
    try {
        const { name, projectId, status = 0, orgId } = req.body;
        if (!name || !projectId) {
            res.status(400).json({ error: 'Name and Project ID are required fields' });
            return;
        }
        const { restrictionsData, isEnterprise, wallet, notifications, thresholds } = await (0, get_upgrade_meta_1.getUpgradeMetaByOrgId)(orgId);
        if (!isEnterprise &&
            restrictionsData?.datasets > 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(wallet?.credits ?? 0).lte(0)
        // ) {
        //   if (notifications?.canSendWalletUsageExceeded) {
        //     await callControlPlane(
        //       `/trusys-emails/limit-reached`,
        //       {
        //         method: 'POST',
        //         params: {
        //           orgId: orgId as string,
        //           type: 'Wallet',
        //           currentUsage: wallet?.credits ?? 0,
        //         },
        //       },
        //       '',
        //     );
        //   }
        //   res.status(400).json({
        //     success: false,
        //     message: ERROR_RESTRICTION_MESSAGE.lowCredits.title,
        //     showToast: true,
        //     toastMetadata: {
        //       text: ERROR_RESTRICTION_MESSAGE.lowCredits.message,
        //     },
        //   });
        //   return;
        // }
        if (!isEnterprise &&
            new decimal_js_1.default(wallet?.credits ?? 0).lte(thresholds?.walletNotificationThreshold ?? 0)
            && notifications?.canSendLowWalletBalance
            && notifications?.canSendLowWalletBalance) {
            await (0, callControlPlaneApi_1.callControlPlane)(`/trusys-emails/limit-reaching`, {
                method: 'POST',
                params: {
                    orgId: orgId,
                    type: 'Wallet',
                    currentUsage: wallet?.credits ?? 0,
                },
            }, '');
        }
        const db = await (0, database_1.getDb)();
        // Check for existing dataset with same name and projectId
        const existing = await db
            .select()
            .from(tables_1.trusysDatasetsTable)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.name, name), (0, drizzle_orm_1.eq)(tables_1.trusysDatasetsTable.projectId, projectId)));
        if (existing.length > 0) {
            res.status(400).json({ error: 'Dataset with this name already exists.' });
            return;
        }
        // Create dataset record
        const [newDataset] = await db
            .insert(tables_1.trusysDatasetsTable)
            .values({
            id: (0, uuid_1.v4)(),
            name,
            projectId,
            workspaceId: orgId,
            status, // 0 for draft, 1 for live
            createdAt: new Date(),
            updatedAt: new Date(),
        })
            .returning();
        // 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_DATASET,
                params: (0, activityLogService_1.buildActivityParams)({
                    dataset_name: { value: name, _id: newDataset.id },
                    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 dataset: ${activityError}`);
        }
        res.status(201).json({ data: newDataset });
    }
    catch (error) {
        console.error('Error creating dataset:', error);
        res.status(500).json({ error: 'Failed to create dataset' });
    }
};
exports.createDataset = createDataset;
//# sourceMappingURL=create-dataset.js.map