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

// Set up uploads directory
const uploadsDir = path.join(process.cwd(), 'uploads');
const bannerDir = path.join(uploadsDir, 'banners');

// Ensure upload directories exist
const ensureDirectoryExists = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
    console.log(`Created directory: ${dir}`);
  }
};

ensureDirectoryExists(uploadsDir);
ensureDirectoryExists(bannerDir);

// Configure storage
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, bannerDir);
  },
  filename: function (req, file, cb) {
    try {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
      const ext = path.extname(file.originalname).toLowerCase();
      const filename = 'banner-' + uniqueSuffix + ext;
      
      // Relative path from the uploads directory
      const relativePath = path.join('banners', filename).replace(/\\/g, '/');
      const fullPath = path.join(bannerDir, filename);
      
      // Ensure the path uses forward slashes
      const cleanRelativePath = relativePath.replace(/\\/g, '/');
      
      // The path should be relative to the uploads directory
      const imagePath = `banners/${filename}`.replace(/\//g, '/');
      
      // Add the file info to the request object for later use
      req.uploadedFile = {
        filename: filename,
        path: imagePath, // Relative path from uploads dir (e.g., 'banners/filename.jpg')
        fullPath: fullPath, // Full system path to the file
        // The URL should be relative to the root, starting with /uploads/
        url: `/uploads/${imagePath}`
      };
      
      console.log('Uploaded file info:', {
        filename,
        cleanRelativePath,
        imagePath,
        fullPath,
        url: req.uploadedFile.url,
        __dirname: __dirname,
        cwd: process.cwd()
      });
      
      cb(null, filename);
    } catch (error) {
      console.error('Error generating filename:', error);
      cb(error);
    }
  }
});

// File filter to accept only images
const fileFilter = (req, file, cb) => {
  try {
    const filetypes = /jpe?g|png|gif|webp/;
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = filetypes.test(file.mimetype);

    if (mimetype && extname) {
      return cb(null, true);
    } else {
      return cb(new BadRequestError('Only image files (jpeg, jpg, png, gif, webp) are allowed!'), false);
    }
  } catch (error) {
    console.error('Error in file filter:', error);
    cb(error);
  }
};

// Initialize multer with configuration
const upload = multer({
  storage: storage,
  limits: { 
    files: 1
  },
  fileFilter: fileFilter
});

// Middleware to handle single file upload
const uploadSingle = upload.single('image');

// Custom middleware to handle multer errors
const handleUpload = (req, res, next) => {
  uploadSingle(req, res, function (err) {
    if (err) {
      // Handle multer errors
      if (err.code === 'LIMIT_FILE_SIZE') {
        return next(new BadRequestError('File size too large. Maximum 5MB allowed.'));
      }
      if (err.code === 'LIMIT_FILE_COUNT') {
        return next(new BadRequestError('Only one file is allowed.'));
      }
      return next(err);
    }
    next();
  });
};

module.exports = handleUpload;
