"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.poisonDocumentsController = void 0;
const logger_1 = __importDefault(require("../../../logger"));
const ragPoisoningService_1 = require("../../services/ragPoisoningService");
const get_upgrade_meta_1 = require("../../../util/get-upgrade-meta");
const decimal_js_1 = __importDefault(require("decimal.js"));
const poisonDocumentsController = async (req, res) => {
    const uploadedFiles = req.files;
    const { goal, type, useAutoStrategy = true, pdfMethod = 'embed', orgId, projectId } = req.body;
    const token = req.headers['x-access-token'] || req.headers.authorization;
    const { wallet, thresholds, isEnterprise, } = await (0, get_upgrade_meta_1.getUpgradeMetaByOrgId)(orgId);
    if (!isEnterprise && new decimal_js_1.default(wallet?.credits ?? 0).lte(0)) {
        res.status(400).json({
            success: false,
            error: 'You have run out of TRU CREDITS',
        });
        return;
    }
    try {
        // Validate required fields
        if (!goal || goal.trim().length === 0) {
            res.status(400).json({
                success: false,
                error: 'Poisoning goal is required',
            });
            return;
        }
        if (!type || !['single', 'zip', 'multiple'].includes(type)) {
            res.status(400).json({
                success: false,
                error: 'Valid file type (single, zip, or multiple) is required',
            });
            return;
        }
        // Extract files based on upload type
        let files = [];
        if (type === 'single' && uploadedFiles.file) {
            files = uploadedFiles.file;
        }
        else if (type === 'zip' && uploadedFiles.zipFile) {
            files = uploadedFiles.zipFile;
        }
        else if (type === 'multiple' && uploadedFiles.files) {
            files = uploadedFiles.files;
        }
        if (!files || files.length === 0) {
            res.status(400).json({
                success: false,
                error: 'No files uploaded for the specified type',
            });
            return;
        }
        if (!token) {
            res.status(401).json({
                success: false,
                error: 'Authentication token required',
            });
            return;
        }
        logger_1.default.info(`Processing RAG poisoning request: type=${type}, files=${files.length}, goal=${goal.substring(0, 50)}..., useAutoStrategy=${useAutoStrategy}`);
        // Process the documents
        const result = await (0, ragPoisoningService_1.poisonDocuments)(files, goal, type, token, useAutoStrategy === 'true' || useAutoStrategy === true, pdfMethod, orgId, projectId);
        if (result.success) {
            logger_1.default.info(`Successfully processed ${result.totalFiles} poisoned files and created ZIP`);
            res.json({
                success: true,
                data: {
                    zipFileUrl: result.zipFileUrl,
                    zipFileName: result.zipFileName,
                    poisonedFiles: result.poisonedFiles,
                    totalFiles: result.totalFiles,
                    goal,
                    type,
                    useAutoStrategy: useAutoStrategy === 'true' || useAutoStrategy === true,
                    pdfMethod,
                    totalCost: result.totalCost,
                },
            });
        }
        else {
            logger_1.default.error(`RAG poisoning failed: ${result.error}`);
            res.status(400).json({
                success: false,
                error: result.error,
            });
        }
        // Clean up uploaded files
        if (files && files.length > 0) {
            const filePaths = files.map((file) => file.path);
            (0, ragPoisoningService_1.cleanupTempFiles)(filePaths);
        }
    }
    catch (error) {
        logger_1.default.error(`Error in poisonDocumentsController: ${error}`);
        res.status(500).json({
            success: false,
            error: 'Internal server error while processing documents',
        });
    }
};
exports.poisonDocumentsController = poisonDocumentsController;
//# sourceMappingURL=poison-documents.js.map