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

// @desc    Upload a file
// @route   POST /api/upload
// @access  Private
exports.uploadFile = (req, res, next) => {
  try {
    if (!req.file) {
      throw new BadRequestError('No file uploaded');
    }

    // Create file URL
    const fileUrl = `${req.protocol}://${req.get('host')}/${req.file.path.replace(/\\/g, '/')}`;

    res.status(200).json({
      success: true,
      data: {
        url: fileUrl,
        path: req.file.path,
        filename: req.file.filename,
        mimetype: req.file.mimetype,
        size: req.file.size
      }
    });
  } catch (error) {
    // If there's an error and a file was uploaded, delete it
    if (req.file) {
      deleteFile(req.file.path).catch(console.error);
    }
    next(error);
  }
};

// @desc    Delete a file
// @route   DELETE /api/upload/:filename
// @access  Private/Admin
exports.deleteFile = async (req, res, next) => {
  try {
    const { filename } = req.params;
    
    if (!filename) {
      throw new BadRequestError('Filename is required');
    }

    // Construct the file path (this should be stored in your database)
    // For this example, we'll assume files are in the uploads directory
    const filePath = `uploads/${filename}`;
    
    await deleteFile(filePath);
    
    res.status(200).json({
      success: true,
      data: {}
    });
  } catch (error) {
    next(error);
  }
};
