"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 multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
// Ensure the uploads directory exists
const uploadDir = 'public';
if (!fs_1.default.existsSync(uploadDir)) {
    console.log('Creating uploads directory...');
    fs_1.default.mkdirSync(uploadDir, { recursive: true });
}
// Get the subfolder based on the field name
const getSubfolder = (fieldName) => {
    switch (fieldName) {
        case 'thumbnails':
            return path_1.default.join(uploadDir, 'upload/thumbnail');
        case 'ktp':
            return path_1.default.join(uploadDir, 'upload/ktp');
        case 'payment':
            return path_1.default.join(uploadDir, 'upload/payment');
        case 'content':
            return path_1.default.join(uploadDir, 'content');
        default:
            return path_1.default.join(uploadDir, 'others');
    }
};
// Ensure the subfolders exist
const subfolders = ['upload/thumbnail', 'upload/ktp', 'upload/payment', 'content', 'others'];
subfolders.forEach((folder) => {
    const dir = path_1.default.join(uploadDir, folder);
    if (!fs_1.default.existsSync(dir)) {
        console.log(`Creating ${dir} directory...`);
        fs_1.default.mkdirSync(dir, { recursive: true });
    }
});
// Set up storage with a dynamic folder based on request or content type
const storage = multer_1.default.diskStorage({
    destination: function (req, file, cb) {
        const folderName = getSubfolder(file.fieldname);
        cb(null, folderName);
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now();
        const ext = path_1.default.extname(file.originalname);
        const sanitizedFilename = path_1.default.basename(file.originalname, ext).replace(/\s+/g, '-').toLowerCase();
        cb(null, `${sanitizedFilename}-${uniqueSuffix}${ext}`);
    },
});
// Set file filter to restrict file types (e.g., images only)
const fileFilter = (req, file, cb) => {
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg'];
    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
    }
    else {
        cb(new Error('Unsupported file format. Only JPEG, PNG, and JPG are allowed'), false);
    }
};
// Set file size limits
const limits = {
    fileSize: 3 * 1024 * 1024, // 3MB
};
// Initialize multer upload
exports.upload = (0, multer_1.default)({
    storage,
    fileFilter,
    limits,
});
