const express = require('express');
const multer = require('multer');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const { uploadFile } = require('../controllers/uploadController');

const router = express.Router();

// Set up storage configuration for multer
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    // Usar una ruta absoluta para evitar problemas
    const uploadPath = path.join(__dirname, '../uploads');
    console.log('Ruta de destino para uploads:', uploadPath);
    cb(null, uploadPath);
  },
  filename: function(req, file, cb) {
    // Generar un nombre único para el archivo
    const fileExt = path.extname(file.originalname);
    const fileName = `${uuidv4()}${fileExt}`;
    console.log('Nombre generado para el archivo:', fileName);
    cb(null, fileName);
  }
});

// File filter
const fileFilter = (req, file, cb) => {
  // Accept images only
  if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
    return cb(new Error('Only image files are allowed!'), false);
  }
  cb(null, true);
};

// Init upload
const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 5 }, // 5MB max file size
  fileFilter: fileFilter
});

router.post('/', upload.single('file'), uploadFile);

module.exports = router;