"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.serveUploadedFileController = exports.uploadAudioController = exports.uploadAudioMiddleware = void 0;
const fs_1 = require("fs");
const multer_1 = __importDefault(require("multer"));
const path_1 = require("path");
const esm_1 = require("../../../esm");
const logger_1 = __importDefault(require("../../../logger"));
// Create uploads directory if it doesn't exist
const UPLOADS_DIR = (0, path_1.join)((0, esm_1.getDirectory)(), 'uploads');
try {
    (0, fs_1.mkdirSync)(UPLOADS_DIR, { recursive: true });
}
catch (error) {
    logger_1.default.warn(`Could not create uploads directory: ${error.message}`);
}
// Configure multer for file uploads
const storage = multer_1.default.diskStorage({
    destination: (req, file, cb) => {
        cb(null, UPLOADS_DIR);
    },
    filename: (req, file, cb) => {
        const timestamp = Date.now();
        const sanitizedFilename = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
        cb(null, `${timestamp}_${sanitizedFilename}`);
    },
});
const upload = (0, multer_1.default)({
    storage,
    limits: {
        fileSize: 10 * 1024 * 1024, // 10MB limit
    },
    fileFilter: (req, file, cb) => {
        const allowedTypes = [
            'audio/mpeg',
            'audio/mp3',
            'audio/wav',
            'audio/wave',
            'audio/mp4',
            'audio/m4a',
            'audio/ogg',
            'audio/webm',
        ];
        const allowedExtensions = /\.(mp3|wav|m4a|ogg|webm)$/i;
        if (allowedTypes.includes(file.mimetype) || allowedExtensions.test(file.originalname)) {
            cb(null, true);
        }
        else {
            cb(new Error('Invalid file type. Please upload an audio file (mp3, wav, m4a, ogg, webm)'));
        }
    },
});
exports.uploadAudioMiddleware = upload.single('audio');
/**
 * Controller for uploading audio files
 */
const uploadAudioController = async (req, res) => {
    try {
        if (!req.file) {
            res.status(400).json({ error: 'No file uploaded' });
            return;
        }
        const { TWILIO_BASE_URL } = process.env;
        const baseUrl = TWILIO_BASE_URL || req.headers.origin || `https://${req.headers.host}`;
        const fileUrl = `${baseUrl}/api/phone/uploads/${req.file.filename}`;
        logger_1.default.info(`[Upload] Audio file uploaded: ${req.file.filename} -> ${fileUrl}`);
        res.json({
            success: true,
            filename: req.file.filename,
            url: fileUrl,
            originalName: req.file.originalname,
            size: req.file.size,
        });
    }
    catch (error) {
        logger_1.default.error(`[Upload] Error uploading file: ${error.message}`);
        res.status(500).json({
            error: 'Failed to upload file',
            message: error.message,
        });
    }
};
exports.uploadAudioController = uploadAudioController;
/**
 * Controller for serving uploaded audio files
 */
const serveUploadedFileController = async (req, res) => {
    try {
        const filename = req.params.filename;
        const filePath = (0, path_1.join)(UPLOADS_DIR, filename);
        // Security: prevent directory traversal
        if (!filePath.startsWith(UPLOADS_DIR)) {
            res.status(403).json({ error: 'Access denied' });
            return;
        }
        const fileBuffer = (0, fs_1.readFileSync)(filePath);
        // Determine content type based on file extension
        const ext = filename.split('.').pop()?.toLowerCase();
        const contentTypeMap = {
            mp3: 'audio/mpeg',
            wav: 'audio/wav',
            m4a: 'audio/mp4',
            ogg: 'audio/ogg',
            webm: 'audio/webm',
        };
        const contentType = contentTypeMap[ext || ''] || 'application/octet-stream';
        res.type(contentType).send(fileBuffer);
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            res.status(404).json({ error: 'File not found' });
            return;
        }
        logger_1.default.error(`[Upload] Error serving file: ${error.message}`);
        res.status(500).json({ error: 'Failed to serve file' });
    }
};
exports.serveUploadedFileController = serveUploadedFileController;
//# sourceMappingURL=audio-upload.js.map