const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Import Sequelize model
const db = require('../models');
const Announcement = db.Announcement;

// 📁 Upload folder setup
const uploadDir = path.join(__dirname, '../uploads/Announcement');
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 });

/**
 * @route POST /api/announcements
 * @desc Create new announcement
 */
router.post('/', upload.single('poster'), async (req, res) => {
  try {
    const {
      title,
      shortDescription,
      fullDescription,
      date,
      time,
      location,
      registrationLink
    } = req.body;

    console.log("Received new announcement:", req.body);

    const newAnnouncement = await Announcement.create({
      title,
      shortDescription,
      fullDescription,
      date,
      time,
      location,
      registrationLink,
      poster: req.file ? `uploads/Announcement/${req.file.filename}` : '',
      order: 0 // ✅ Fixed: was Date.now(), now safe value
    });

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

/**
 * @route GET /api/announcements
 * @desc Get all announcements (ordered)
 */
router.get('/', async (req, res) => {
  try {
    const announcements = await Announcement.findAll({
      order: [['order', 'ASC']]
    });
    res.json(announcements);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching announcements' });
  }
});

/**
 * @route DELETE /api/announcements/:id
 * @desc Delete an announcement
 */
router.delete('/:id', async (req, res) => {
  try {
    const announcement = await Announcement.findByPk(req.params.id);
    if (!announcement) return res.status(404).json({ message: 'Not found' });

    if (announcement.poster && fs.existsSync(announcement.poster)) {
      fs.unlinkSync(announcement.poster);
    }

    await announcement.destroy();
    res.json({ message: 'Deleted successfully' });
  } catch (error) {
    console.error('Delete error:', error);
    res.status(500).json({ message: 'Server error' });
  }
});

/**
 * @route PUT /api/announcements/reorder
 * @desc Reorder announcements by ID list
 */
router.put('/reorder', async (req, res) => {
  try {
    const { orderedIds } = req.body;

    for (let i = 0; i < orderedIds.length; i++) {
      await Announcement.update(
        { order: i },
        { where: { id: orderedIds[i] } }
      );
    }

    res.json({ message: 'Order updated' });
  } catch (error) {
    console.error('Reorder error:', error);
    res.status(500).json({ message: 'Failed to update order' });
  }
});

module.exports = router;
