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

const router = express.Router();
const db = require('../models');
const Event = db.Event;
const EventYear = db.EventYear;

// 📂 Ensure Events folder exists
const uploadDir = path.join(__dirname, '../uploads/Events');
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });

// 📸 Multer config
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const upload = multer({ storage });

/**
 * 🔄 GET /api/events
 * Fetch all years with events
 */
router.get('/', async (req, res) => {
  try {
    const years = await EventYear.findAll({
      include: [{ model: Event }],
      order: [['label', 'DESC']]
    });
    res.json(years);
  } catch (err) {
    console.error('Fetch years error:', err);
    res.status(500).json({ message: 'Failed to fetch event years' });
  }
});

/**
 * ➕ POST /api/events/year
 * Add new year
 */
router.post('/year', async (req, res) => {
  try {
    const { label } = req.body;
    const newYear = await EventYear.create({ label });
    res.status(201).json(newYear);
  } catch (err) {
    console.error('Add year error:', err);
    res.status(500).json({ message: 'Failed to create year' });
  }
});

/**
 * ❌ DELETE /api/events/year/:id
 * Delete year and its events
 */
router.delete('/year/:id', async (req, res) => {
  try {
    await EventYear.destroy({ where: { id: req.params.id } });
    res.json({ message: 'Year deleted' });
  } catch (err) {
    console.error('Delete year error:', err);
    res.status(500).json({ message: 'Failed to delete year' });
  }
});

/**
 * 📤 POST /api/events
 * Upload event (poster + optional report)
 */
router.post('/', upload.fields([{ name: 'poster' }, { name: 'report' }]), async (req, res) => {
  try {
    const { name, yearId } = req.body;
    const posterFile = req.files.poster?.[0];
    const reportFile = req.files.report?.[0];

    if (!posterFile || !name || !yearId) {
      return res.status(400).json({ message: 'Missing required fields' });
    }

    const posterPath = `uploads/Events/${posterFile.filename}`;
    const reportPath = reportFile ? `uploads/Events/${reportFile.filename}` : null;

    const newEvent = await Event.create({
      name,
      yearId,
      posterPath,
      reportPath
    });

    res.status(201).json(newEvent);
  } catch (err) {
    console.error('Upload event error:', err);
    res.status(500).json({ message: 'Failed to upload event' });
  }
});

/**
 * ❌ DELETE /api/events/:id
 * Delete an event
 */
router.delete('/:id', async (req, res) => {
  try {
    const event = await Event.findByPk(req.params.id);
    if (!event) return res.status(404).json({ message: 'Not found' });

    // Delete files if they exist
    if (event.posterPath && fs.existsSync(path.join(__dirname, '..', event.posterPath))) {
      fs.unlinkSync(path.join(__dirname, '..', event.posterPath));
    }

    if (event.reportPath && fs.existsSync(path.join(__dirname, '..', event.reportPath))) {
      fs.unlinkSync(path.join(__dirname, '..', event.reportPath));
    }

    await event.destroy();
    res.json({ message: 'Event deleted' });
  } catch (err) {
    console.error('Delete event error:', err);
    res.status(500).json({ message: 'Failed to delete event' });
  }
});

module.exports = router;
