import multer from 'multer';
import path from 'path';
import fs from 'fs';

export const ALLOWED_FILE_TYPES = [
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/vnd.ms-powerpoint',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'image/jpeg',
  'image/png',
  'image/gif',
  'image/webp',
  'text/plain',
  'text/csv',
];

function createFileFilter(allowedTypes, errorMessage) {
  return (req, file, cb) => {
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error(errorMessage));
    }
  };
}

function createDiskStorage(uploadsDir) {
  if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
  }

  return multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, uploadsDir);
    },
    filename: (req, file, cb) => {
      const sanitized = path.basename(file.originalname).replace(/[^a-zA-Z0-9._-]/g, '_');
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
      cb(null, uniqueSuffix + '-' + sanitized);
    },
  });
}

export function createUpload({ maxSizeMB = 20, allowedTypes, errorMessage, diskPath } = {}) {
  const opts = {
    storage: diskPath ? createDiskStorage(diskPath) : multer.memoryStorage(),
    limits: { fileSize: maxSizeMB * 1024 * 1024 },
  };

  if (allowedTypes) {
    opts.fileFilter = createFileFilter(
      allowedTypes,
      errorMessage || 'Nepovolený typ súboru.',
    );
  }

  return multer(opts);
}
