import { Router } from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { MediaModel } from '../database/models/MediaModel';

const router = Router();

// Configuración de Multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(__dirname, '../../../../uploads');
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ 
  storage,
  limits: { fileSize: 50 * 1024 * 1024 }, // 50MB
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|mp4|webm|pdf/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    if (extname && mimetype) {
      return cb(null, true);
    }
    cb(new Error('Formato de archivo no permitido'));
  }
});

// Endpoint de subida
router.post('/upload', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'No se ha subido ningún archivo' });
    }

    const { filename, originalname, mimetype, size, path: filePath } = req.file;
    const url = `/api/media/static/${filename}`;

    const media = await MediaModel.create({
      filename,
      originalname,
      mimetype,
      size,
      path: filePath,
      url,
      category: req.body.category
    });

    res.status(201).json(media);
  } catch (error: any) {
    res.status(500).json({ error: error.message });
  }
});

// Listar medios
router.get('/', async (req, res) => {
  try {
    const media = await MediaModel.find().sort({ createdAt: -1 });
    res.json(media);
  } catch (error: any) {
    res.status(500).json({ error: error.message });
  }
});

// Eliminar medio
router.delete('/:id', async (req, res) => {
  try {
    const media = await MediaModel.findById(req.params.id);
    if (!media) {
      return res.status(404).json({ error: 'Archivo no encontrado' });
    }

    // Eliminar archivo físico
    if (fs.existsSync(media.path)) {
      fs.unlinkSync(media.path);
    }

    // Eliminar registro
    await MediaModel.findByIdAndDelete(req.params.id);

    res.json({ message: 'Archivo eliminado correctamente' });
  } catch (error: any) {
    res.status(500).json({ error: error.message });
  }
});

export default router;
