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

// Create uploads directory if it doesn't exist
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // We'll generate the final filename for the thumbnail here
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    // Save with .png extension always (you can keep original if you want)
    cb(null, 'profilePic-' + uniqueSuffix + '.png');
  }
});

// File filter to allow only png, jpg, jpeg
function fileFilter(req, file, cb) {
  const allowedTypes = /jpeg|jpg|png/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);
  if (extname && mimetype) {
    cb(null, true);
  } else {
    cb(new Error('Only .png, .jpg and .jpeg formats allowed!'));
  }
}

const upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
      // Temporarily save original with a temp name to resize it
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
      cb(null, 'temp-' + uniqueSuffix + path.extname(file.originalname));
    }
  }),
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 1
  },
  fileFilter
});

// Middleware to resize image and replace original with thumbnail
async function resizeProfilePic(req, res, next) {
  if (!req.file) return next();

  const tempPath = req.file.path;
  // Final filename for the thumbnail
  const thumbFilename = 'profilePic-' + Date.now() + '-' + Math.round(Math.random() * 1E9) + '.png';
  const thumbPath = path.join(uploadDir, thumbFilename);

  try {
    await sharp(tempPath)
      .resize(400, 400)
      .png() // convert all to PNG to keep consistent format
      .toFile(thumbPath);

    // Delete the original uploaded temp file
    fs.unlinkSync(tempPath);

    // Replace req.file info to point to the new thumbnail file
    req.file.filename = thumbFilename;
    req.file.path = thumbPath;

    next();
  } catch (err) {
    // Delete temp file if something goes wrong
    if (fs.existsSync(tempPath)) {
      fs.unlinkSync(tempPath);
    }
    next(err);
  }
}

module.exports = { upload, resizeProfilePic };
