const path = require("path");

// ==========================================
// Allowed MIME Types
// ==========================================

const ALLOWED_IMAGE_TYPES = [
    "image/jpeg",
    "image/jpg",
    "image/png"
];

// ==========================================
// Validate File Type
// ==========================================

function validateFileType(file) {

    if (!file) {
        return {
            valid: false,
            message: "No file uploaded."
        };
    }

    if (!ALLOWED_IMAGE_TYPES.includes(file.mimetype)) {
        return {
            valid: false,
            message: "Only JPG and PNG images are allowed."
        };
    }

    return { valid: true };
}

// ==========================================
// Validate File Size
// ==========================================

function validateFileSize(file, maxSize) {

    if (file.size > maxSize) {
        return {
            valid: false,
            message: `File too large. Max allowed size is ${maxSize / (1024 * 1024)}MB`
        };
    }

    return { valid: true };
}

// ==========================================
// Sanitize Filename
// ==========================================

function sanitizeFileName(originalName) {

    const ext = path.extname(originalName);

    const base = path
        .basename(originalName, ext)
        .replace(/[^a-zA-Z0-9]/g, "_")
        .toLowerCase();

    return `${base}_${Date.now()}${ext}`;
}

module.exports = {
    validateFileType,
    validateFileSize,
    sanitizeFileName
};