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

/**
 * Shared multer storage configuration for file uploads.
 * This configuration provides consistent file storage settings
 * across multiple endpoints that handle file uploads.
 *
 * Key features:
 * - Stores uploaded files in './uploads' directory
 * - Generates unique, safe filenames to prevent collisions
 * - Normalizes field names for filesystem compatibility
 */
export const commonStorage = diskStorage({
  // Destination directory for uploaded files
  // All files will be stored in './uploads' relative to project root
  destination: './uploads',

  // Filename generation function
  // Creates unique, safe filenames to prevent overwrites and naming conflicts
  filename: (req, file, cb) => {
    // Generate a unique suffix using timestamp and random number
    // This ensures files with the same original name don't overwrite each other
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);

    // Extract the original file extension for type preservation
    const ext = extname(file.originalname);

    // Normalize field name by replacing brackets with underscores
    // This prevents filesystem issues with special characters in fieldnames
    // Example: 'photos[0]' becomes 'photos_0_'
    const safeFieldName = file.fieldname.replace(/\[|\]/g, '_');

    // Construct final filename format: {safeFieldName}-{timestamp}-{random}.{ext}
    // Example: 'photos_0_-1234567890123-987654321.jpg'
    cb(null, `${safeFieldName}-${uniqueSuffix}${ext}`);
  },
});
