import multer from "multer";
import path from "path";
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, "./public/uploads");
    },
    filename: function(req, file, cb) {
        const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
        cb(null, Date.now() + '-' + sanitizedName);
    }
});

const memoryStorage = multer.memoryStorage();


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

// Audio MIME types that are actually video containers
const ALLOWED_AUDIO_VIDEO_CONTAINERS = [
    "audio/x-ms-asf", // .wmv (sometimes detected as audio)
    "audio/mp4" // Some MP4 videos detected as audio
];

const ALLOWED_IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
// Allowed video extensions - only MP4, MOV, and M4V
const ALLOWED_VIDEO_EXTENSIONS = ['.mp4', '.mov', '.m4v'];
const imageFileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
    const fileExtension = path.extname(file.originalname).toLowerCase();
    if (!ALLOWED_IMAGE_TYPES.includes(file.mimetype)) {
        return cb(new Error(`Invalid file type. Only images are allowed: ${ALLOWED_IMAGE_EXTENSIONS.join(', ')}`));
    }

    if (!ALLOWED_IMAGE_EXTENSIONS.includes(fileExtension)) {
        return cb(new Error(`Invalid file extension. Only images are allowed: ${ALLOWED_IMAGE_EXTENSIONS.join(', ')}`));
    }

    cb(null, true);
};

export const fileUpload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 10 // 10MB for images
    },
    fileFilter: imageFileFilter
});

// Memory storage upload for S3 (images and videos)
// Dynamically adjusts size limit based on file type
export const s3FileUpload = multer({
    storage: memoryStorage,
    limits: {
        fileSize: 1024 * 1024 * 50 // 50MB max (videos)
    },
    fileFilter: (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
        const fileExtension = path.extname(file.originalname).toLowerCase();

        // Check if it's an image or video
        const isImage = ALLOWED_IMAGE_TYPES.includes(file.mimetype) && ALLOWED_IMAGE_EXTENSIONS.includes(fileExtension);
        // Accept any MIME type starting with 'video/' OR audio containers that hold video
        const isVideo = (file.mimetype.startsWith('video/') || ALLOWED_AUDIO_VIDEO_CONTAINERS.includes(file.mimetype))
                        && ALLOWED_VIDEO_EXTENSIONS.includes(fileExtension);

        if (!isImage && !isVideo) {
            return cb(new Error(`Invalid file type. Only images and videos are allowed. Supported extensions: ${ALLOWED_IMAGE_EXTENSIONS.concat(ALLOWED_VIDEO_EXTENSIONS).join(', ')}`));
        }

        // Note: File size validation happens in multer limits above
        // For more granular control (10MB images, 50MB videos), we handle this in the controller
        cb(null, true);
    }
});
