import { BadRequestException } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { diskStorage } from "multer";

export enum FileFilterEnum {
    IMAGE = 'image',
    VIDEO = 'video',
    AUDIO = 'audio',
}


/**
 * 
 * @param fieldName  The name of the field
 * @param folderName  The name of the folder
 * @param filter  The type of the file
 * @returns  The file interceptor
 */
export function fileInterceptor(fieldName: string, folderName: string, filter?: FileFilterEnum) {
    return FileInterceptor(fieldName, {
        storage: diskStorage({
            destination: './public/' + folderName + '/',
            filename: (req, file, cb) => { cb(null, `${Date.now()}-${file.originalname}`) }
        }),
        fileFilter: (req, file, cb) => {
            if (filter === FileFilterEnum.IMAGE) {
                if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
                    return cb(new BadRequestException('Only image files are allowed!'), false);
                }
            }
            else if (filter === FileFilterEnum.VIDEO) {
                if (!file.originalname.match(/\.(mp4|mov|avi|wmv|flv|3gp)$/)) {
                    return cb(new BadRequestException('Only video files are allowed!'), false);
                }
            }
            else if (filter === FileFilterEnum.AUDIO) {
                if (!file.originalname.match(/\.(mp3|wav)$/)) {
                    return cb(new BadRequestException('Only audio files are allowed!'), false);
                }
            }
            cb(null, true);
        }
    });
} 