"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.uploadFileToAzure = exports.uploadFilesToAzure = exports.uploadDocumentToAzure = exports.uploadDocumentsToAzure = exports.uploadAudioFile = exports.uploadAudioFiles = void 0;
const fs = __importStar(require("fs"));
// import { v4 as uuidv4 } from 'uuid';
const callControlPlaneApi_1 = require("../callContolPlane/callControlPlaneApi");
const uploadAudioFiles = async (files, token, folderName) => {
    try {
        const formData = new FormData();
        formData.append('folderName', folderName);
        const filesToRead = files.filter((file) => file?.wavFilePath &&
            String(file.wavFilePath).trim() &&
            fs.existsSync(file.wavFilePath));
        if (filesToRead.length === 0) {
            return {};
        }
        filesToRead.forEach((file) => {
            const fileBuffer = fs.readFileSync(file.wavFilePath);
            const fileBlob = new Blob([new Uint8Array(fileBuffer)], { type: 'text/plain' });
            // Add uuid to the file name before uploading
            const uniqueFileName = `${file?.fileName}`;
            formData.append('file', fileBlob, uniqueFileName);
        });
        const response = await (0, callControlPlaneApi_1.callControlPlaneWithFormData)('/upload', formData, {}, token);
        if (response?.error) {
            throw new Error(response?.error);
        }
        // Create a mapping of fileName to URL
        const urlMap = {};
        filesToRead.forEach((file, index) => {
            urlMap[file.fileName] = response?.response?.uploads?.[index]?.url || '';
            // Clean up the base64 file after successful upload
            try {
                fs.unlinkSync(file.wavFilePath);
            }
            catch (error) {
                console.error(`Error deleting base64 file ${file.wavFilePath}:`, error);
            }
        });
        return urlMap;
    }
    catch (error) {
        console.error('Error uploading audio files:', error);
        throw error;
    }
};
exports.uploadAudioFiles = uploadAudioFiles;
// Keep the original function for backward compatibility
const uploadAudioFile = async (wavFilePath, fileName, token) => {
    const result = await (0, exports.uploadAudioFiles)([{ wavFilePath, fileName }], token, fileName);
    return result[fileName];
};
exports.uploadAudioFile = uploadAudioFile;
/**
 * Upload documents to Azure storage
 * @param files Array of document files to upload
 * @param token Authentication token
 * @param folderName Folder name in Azure storage
 * @returns Promise<Record<string, string>> Mapping of fileName to URL
 */
const uploadDocumentsToAzure = async (files, token, folderName) => {
    try {
        const formData = new FormData();
        formData.append('folderName', folderName);
        files.forEach((file) => {
            const fileBuffer = fs.readFileSync(file.filePath);
            const contentType = file.contentType || 'text/plain';
            const fileBlob = new Blob([new Uint8Array(fileBuffer)], { type: contentType });
            formData.append('file', fileBlob, file.fileName);
        });
        const response = await (0, callControlPlaneApi_1.callControlPlaneWithFormData)('/upload', formData, {}, token);
        if (response?.error) {
            throw new Error(response?.error);
        }
        // Create a mapping of fileName to URL
        const urlMap = {};
        files.forEach((file, index) => {
            urlMap[file.fileName] = response?.response?.uploads?.[index]?.url || '';
            // Clean up the temporary file after successful upload
            try {
                fs.unlinkSync(file.filePath);
            }
            catch (error) {
                console.error(`Error deleting temporary file ${file.filePath}:`, error);
            }
        });
        return urlMap;
    }
    catch (error) {
        console.error('Error uploading documents to Azure:', error);
        throw error;
    }
};
exports.uploadDocumentsToAzure = uploadDocumentsToAzure;
/**
 * Upload a single document to Azure storage
 * @param filePath Path to the file to upload
 * @param fileName Name for the file in storage
 * @param token Authentication token
 * @param folderName Folder name in Azure storage
 * @param contentType MIME type of the file
 * @returns Promise<string> URL of the uploaded file
 */
const uploadDocumentToAzure = async (filePath, fileName, token, folderName, contentType = 'text/plain') => {
    const result = await (0, exports.uploadDocumentsToAzure)([{ filePath, fileName, contentType }], token, folderName);
    return result[fileName];
};
exports.uploadDocumentToAzure = uploadDocumentToAzure;
/**
 * Generic function to upload any type of file to Azure storage
 * @param files Array of files to upload
 * @param token Authentication token
 * @param folderName Folder name in Azure storage
 * @returns Promise<Record<string, string>> Mapping of fileName to URL
 */
const uploadFilesToAzure = async (files, token, folderName, controlPlaneUrl) => {
    try {
        const formData = new FormData();
        formData.append('folderName', folderName);
        files.forEach((file) => {
            const fileBuffer = fs.readFileSync(file.filePath);
            const contentType = file.contentType || 'text/plain';
            const fileBlob = new Blob([new Uint8Array(fileBuffer)], { type: contentType });
            // Add UUID prefix if requested
            const finalFileName = file.fileName;
            formData.append('file', fileBlob, finalFileName);
        });
        // Add privateContainer parameter to form data
        const privateContainer = files[0]?.privateContainer !== false; // Default to true if not specified
        formData.append('privateContainer', privateContainer.toString());
        // Add generateSasToken parameter to form data
        const generateSasToken = files[0]?.generateSasToken === true; // Default to false if not specified
        formData.append('generateSasToken', generateSasToken.toString());
        const response = await (0, callControlPlaneApi_1.callControlPlaneWithFormData)('/upload', formData, {}, token, controlPlaneUrl);
        if (response?.error) {
            throw new Error(response?.error);
        }
        // Create a mapping of fileName to URL
        const urlMap = {};
        files.forEach((file, index) => {
            urlMap[file.fileName] = response?.response?.uploads?.[index]?.url || '';
            // Clean up the file after successful upload if requested
            if (file.cleanupAfterUpload) {
                try {
                    fs.unlinkSync(file.filePath);
                }
                catch (error) {
                    console.error(`Error deleting file ${file.filePath}:`, error);
                }
            }
        });
        return urlMap;
    }
    catch (error) {
        console.error('Error uploading files to Azure:', error);
        throw error;
    }
};
exports.uploadFilesToAzure = uploadFilesToAzure;
/**
 * Upload a single file to Azure storage using the generic function
 * @param filePath Path to the file to upload
 * @param fileName Name for the file in storage
 * @param token Authentication token
 * @param folderName Folder name in Azure storage
 * @param contentType MIME type of the file
 * @param addUuid Whether to add UUID prefix to filename
 * @param cleanupAfterUpload Whether to delete the file after upload
 * @param privateContainer Whether to use private container (default: true)
 * @param generateSasToken Whether to generate SAS token for the uploaded file (default: false)
 * @returns Promise<string> URL of the uploaded file
 */
const uploadFileToAzure = async (filePath, fileName, token, folderName, contentType = 'text/plain', addUuid = false, cleanupAfterUpload = true, privateContainer = true, generateSasToken = false, controlPlaneUrl) => {
    const result = await (0, exports.uploadFilesToAzure)([
        {
            filePath,
            fileName,
            contentType,
            addUuid,
            cleanupAfterUpload,
            privateContainer,
            generateSasToken,
        },
    ], token, folderName, controlPlaneUrl);
    return result[fileName];
};
exports.uploadFileToAzure = uploadFileToAzure;
//# sourceMappingURL=index.js.map