// file.interceptor.ts
import { BadRequestException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { v4 as uuidv4 } from 'uuid';

export const fileInterceptor = (fieldName: string, dest: string, validExt: string[]) =>
  FileInterceptor(fieldName, {
    storage: diskStorage({
      destination: (req, file, callback) => {
        callback(null, dest);
      },
      filename: (req, file, callback) => {
        const extension = extname(file.originalname);
        if (!validExt.includes(extension)) {
          return callback(new BadRequestException('Only image files are allowed!'), '');
        }
        const uniqueFilename = `${uuidv4()}${extension}`;
        callback(null, uniqueFilename);
      },
    }),
  });
