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

const db = require('../models');
const TeamYear = db.TeamYear;
const OurTeamMember = db.OurTeamMember;

// 🗂️ Uploads folder setup
const uploadDir = path.join(__dirname, '../uploads/OurTeam');
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/ourteam
 * Get all team data grouped by year and role
 */
router.get('/', async (req, res) => {
  try {
    const years = await TeamYear.findAll({
      include: [{ model: OurTeamMember }],
      order: [['label', 'DESC']]
    });
    res.json(years);
  } catch (err) {
    console.error('Fetch team error:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

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

/**
 * ❌ DELETE /api/ourteam/year/:id
 * Delete a team year and its members
 */
router.delete('/year/:id', async (req, res) => {
  try {
    await TeamYear.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/ourteam/member
 * Add a member to a year (with image)
 */
router.post('/member', upload.single('image'), async (req, res) => {
  try {
    const { name, title, role, yearId } = req.body;

    const newMember = await OurTeamMember.create({
      name,
      title,
      role,
      yearId,
      imagePath: req.file ? `uploads/OurTeam/${req.file.filename}` : ''
    });

    res.status(201).json(newMember);
  } catch (err) {
    console.error('Add member error:', err);
    res.status(500).json({ message: 'Failed to add member' });
  }
});

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

    if (fs.existsSync(member.imagePath)) {
      fs.unlinkSync(member.imagePath);
    }

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

module.exports = router;
