import { Router } from 'express';
import auth from '../middleware/auth.js';
import upload from '../middleware/upload.js';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const router = Router();

router.post('/', auth, upload.single('file'), (req, res) => {
  if (!req.file) return res.status(400).json({ message: 'No file uploaded.' });
  res.status(201).json({
    message:  'File uploaded successfully.',
    filename: req.file.filename,
    path:     `public/uploads/${req.file.filename}`,
    url:      `/public/uploads/${req.file.filename}`,
  });
});

router.delete('/:filename', auth, (req, res) => {
  const filePath = path.join(__dirname, '..', 'public', 'uploads', req.params.filename);
  if (!fs.existsSync(filePath)) return res.status(404).json({ message: 'File not found.' });
  fs.unlinkSync(filePath);
  res.json({ message: 'File deleted.' });
});

export default router;