"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertToAudioController = void 0;
const logger_1 = __importDefault(require("../../../logger"));
const textToAudioService_1 = require("../../services/textToAudioService");
const get_upgrade_meta_1 = require("../../../util/get-upgrade-meta");
const decimal_js_1 = __importDefault(require("decimal.js"));
const convertToAudioController = async (req, res) => {
    const uploadedFiles = req.files;
    const { addFillerWords, emotions, accent, orgId, projectId, outputFormat, sampleRate } = 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 {
        // Extract the CSV file
        let csvFile;
        if (uploadedFiles.textFile && uploadedFiles.textFile.length > 0) {
            csvFile = uploadedFiles.textFile[0];
        }
        if (!csvFile) {
            res.status(400).json({
                success: false,
                error: 'CSV file is required',
            });
            return;
        }
        if (!token) {
            res.status(401).json({
                success: false,
                error: 'Authentication token required',
            });
            return;
        }
        if (!orgId || !projectId) {
            res.status(400).json({
                success: false,
                error: 'Organization ID and Project ID are required',
            });
            return;
        }
        logger_1.default.info(`Processing text-to-audio conversion: file=${csvFile.originalname}`);
        // Parse options
        const options = {
            addFillerWords,
            outputFormat: outputFormat || 'wav',
            sampleRate: sampleRate || '44100',
        };
        if (emotions) {
            try {
                options.emotions = typeof emotions === 'string' ? JSON.parse(emotions) : emotions;
            }
            catch (e) {
                logger_1.default.warn(`Failed to parse emotions: ${e}`);
            }
        }
        if (accent) {
            try {
                options.accent = typeof accent === 'string' ? JSON.parse(accent) : accent;
            }
            catch (e) {
                logger_1.default.warn(`Failed to parse accent: ${e}`);
            }
        }
        // Convert CSV to audio
        const result = await (0, textToAudioService_1.convertCsvToAudio)(csvFile.path, token, orgId, projectId, options);
        if (result.success) {
            logger_1.default.info(`Successfully converted ${result.totalFiles} audio files and created ZIP`);
            res.json({
                success: true,
                data: {
                    zipFileUrl: result.zipFileUrl,
                    zipFileName: result.zipFileName,
                    audioFiles: result.audioFiles,
                    totalFiles: result.totalFiles,
                    totalCost: result.totalCost,
                },
            });
        }
        else {
            logger_1.default.error(`Text-to-audio conversion failed: ${result.error}`);
            res.status(400).json({
                success: false,
                error: result.error,
            });
        }
        // Clean up uploaded CSV file
        if (csvFile) {
            (0, textToAudioService_1.cleanupTempFiles)([csvFile.path]);
        }
    }
    catch (error) {
        logger_1.default.error(`Error in convertToAudioController: ${error}`);
        res.status(500).json({
            success: false,
            error: 'Internal server error while converting text to audio',
        });
        // Clean up on error
        if (uploadedFiles.textFile && uploadedFiles.textFile.length > 0) {
            const filePaths = uploadedFiles.textFile.map((file) => file.path);
            (0, textToAudioService_1.cleanupTempFiles)(filePaths);
        }
    }
};
exports.convertToAudioController = convertToAudioController;
//# sourceMappingURL=convert-to-audio.js.map