const fs = require('fs');
const path = require('path');
const multer = require('multer');

const uploadRoot = path.resolve(__dirname, '../../uploads');
const customerPhotosDirectory = path.join(uploadRoot, 'customer-photos');
const idProofsDirectory = path.join(uploadRoot, 'id-proofs');
const jewelryDirectory = path.join(uploadRoot, 'jewels');

fs.mkdirSync(customerPhotosDirectory, {recursive: true});
fs.mkdirSync(idProofsDirectory, {recursive: true});
fs.mkdirSync(jewelryDirectory, {recursive: true});

function createStorage(directory) {
  return multer.diskStorage({
    destination: (_request, _file, callback) => callback(null, directory),
    filename: (_request, file, callback) => {
      const extension = path.extname(file.originalname || '').toLowerCase() || '.jpg';
      const safeName = `${Date.now()}-${Math.round(Math.random() * 1e9)}${extension}`;
      callback(null, safeName);
    },
  });
}

const uploadCustomerFiles = multer({
  storage: multer.diskStorage({
    destination: (_request, file, callback) => {
      callback(null, file.fieldname === 'idProofPhoto' ? idProofsDirectory : customerPhotosDirectory);
    },
    filename: (_request, file, callback) => {
      const extension = path.extname(file.originalname || '').toLowerCase() || '.jpg';
      callback(null, `${Date.now()}-${Math.round(Math.random() * 1e9)}${extension}`);
    },
  }),
  limits: {fileSize: 8 * 1024 * 1024, files: 2},
  fileFilter: (_request, file, callback) => {
    if (file.mimetype && file.mimetype.startsWith('image/')) {
      callback(null, true);
      return;
    }
    callback(new Error('Only image files are allowed.'));
  },
});

module.exports = {
  uploadCustomerFiles,
  uploadRoot,
  customerPhotosDirectory,
  idProofsDirectory,
  jewelryDirectory,
  createStorage,
};
