"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.upload = void 0;
const fs_1 = __importDefault(require("fs"));
const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const errorHandler_1 = require("../src/middleware/errorHandler");
const crypto_1 = __importDefault(require("crypto"));
const upload = (folder, filePath) => {
    let allowedExtensions = [];
    let message = "Invalid file type. Only images are allowed!";
    if (filePath === "files") {
        allowedExtensions = [".mp4", ".pdf"];
        message = "Invalid file type. Only [mp4 , pdf] are allowed!";
    }
    else if (filePath === "images")
        allowedExtensions = [".jpg", ".jpeg", ".png", ".gif", ".webp"];
    // Ensure the folder exists
    const folderPath = filePath
        ? `public/storage/${filePath}/${folder}`
        : `public/storage/${folder}`;
    if (!fs_1.default.existsSync(folderPath)) {
        try {
            fs_1.default.mkdirSync(folderPath, { recursive: true });
        }
        catch (err) {
            if (err instanceof Error) {
                throw new errorHandler_1.AppError(500, err.message ?? "Failed to create upload directory");
            }
            else {
                throw new errorHandler_1.AppError(500, "Unknown error occurred while creating upload directory");
            }
        }
    }
    const storage = multer_1.default.diskStorage({
        destination: (_req, _file, cb) => {
            cb(null, folderPath);
        },
        filename: (_req, file, cb) => {
            const ext = path_1.default.extname(file.originalname).toLowerCase();
            const uniqueHash = crypto_1.default.randomBytes(20).toString("hex");
            cb(null, `${uniqueHash}${ext}`);
        },
    });
    return (0, multer_1.default)({
        storage,
        limits: { fileSize: 50 * 1024 * 1024 }, // 10MB file limit
    });
};
exports.upload = upload;
