const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { BadRequestError } = require('../utils/errors');

const uploadDir = path.join(process.cwd(), 'public', 'uploads', 'deposits');

if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const allowedMimeTypes = [
  'application/pdf',
  'image/jpeg',
  'image/jpg',
  'image/png',
  'image/webp',
];

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },

  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname || '').toLowerCase();
    const baseName = path
      .basename(file.originalname || 'document', ext)
      .replace(/[^a-zA-Z0-9-_]/g, '_')
      .slice(0, 60);

    const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1e9)}-${baseName}${ext}`;
    cb(null, uniqueName);
  },
});

const fileFilter = (req, file, cb) => {
  if (!allowedMimeTypes.includes(file.mimetype)) {
    return cb(
      new BadRequestError('Only PDF, JPG, JPEG, PNG and WEBP files are allowed'),
      false
    );
  }

  cb(null, true);
};

const uploadDeposit= multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 500 * 1024 * 1024, // 5MB
    files: 1,
  },
}).single('proof');

module.exports = uploadDeposit;