import { diskStorage } from 'multer';
import { extname } from 'path';
import { BadRequestException } from '@nestjs/common';

// Extensions autorisées
const ALLOWED_EXTENSIONS = ['.pdf', '.jpg', '.jpeg', '.png'];
const MAX_SIZE_MB = 5;

export const multerConfig = {
  storage: diskStorage({
    destination: './uploads/leaves',
    filename: (req, file, cb) => {
      const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
      const ext = extname(file.originalname).toLowerCase();
      cb(null, `leave-${uniqueSuffix}${ext}`);
    },
  }),
  limits: {
    fileSize: MAX_SIZE_MB * 1024 * 1024, // 5 Mo max
  },
  fileFilter: (req: any, file: Express.Multer.File, cb: any) => {
    const ext = extname(file.originalname).toLowerCase();
    if (!ALLOWED_EXTENSIONS.includes(ext)) {
      return cb(
        new BadRequestException(
          `Extension non autorisée. Formats acceptés : ${ALLOWED_EXTENSIONS.join(', ')}`
        ),
        false,
      );
    }
    cb(null, true);
  },
};