import { diskStorage } from 'multer';
import { extname } from 'path';

/**
 * multerDiskStorage
 * ------------------
 * Creates a Multer disk storage configuration with:
 * - Custom destination path
 * - Collision-safe file naming strategy
 *
 * @param destinationPath Absolute or relative directory path
 * @returns Multer disk storage configuration
 */
export const multerDiskStorage = (destinationPath: string) =>
  diskStorage({
    /**
     * Directory where uploaded files will be stored
     */
    destination: destinationPath,

    /**
     * Filename generator
     * Uses timestamp + random number to avoid filename collisions
     */
    filename: (req, file, cb) => {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);

      // Preserve original file extension
      const extension = extname(file.originalname);

      cb(null, `${file.fieldname}-${uniqueSuffix}${extension}`);
    },
  });

/**
 * fileTypeFilter
 * --------------
 * Validates uploaded files against a whitelist of allowed extensions.
 *
 * Allowed file types:
 * - Images: jpg, jpeg, png, webp
 * - Documents: pdf, doc, docx
 * - Videos: mp4
 *
 * @param req Express request object
 * @param file Uploaded file metadata
 * @param cb Multer callback
 */
export const fileTypeFilter = (
  req: Express.Request,
  file: Express.Multer.File,
  cb: Function,
) => {
  // Regex whitelist for allowed file extensions
  const allowedExtensions = /\.(jpg|jpeg|png|webp|pdf|doc|docx|mp4)$/i;

  // Validate file extension using original filename
  if (!allowedExtensions.test(file.originalname)) {
    return cb(new Error('Invalid file type'), false);
  }

  // Accept file
  cb(null, true);
};

/**
 * MAX_FILE_SIZE
 * -------------
 * Maximum allowed file size for uploads.
 *
 * Value:
 * - 50MB (converted to bytes)
 */
export const MAX_FILE_SIZE = 50 * 1024 * 1024;
