const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const db = require('../models');
const TeamMember = db.TeamMember;

// Create upload folder if not exists
const uploadDir = path.join(__dirname, '../uploads/Team');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// Multer setup
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 });

// 📥 Upload new team member
router.post('/', upload.single('image'), async (req, res) => {
  try {
    const { name, title } = req.body;
    const imagePath = `uploads/Team/${req.file.filename}`;

    const member = await TeamMember.create({
      name,
      title,
      imagePath
    });

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

// 📤 Get all team members
router.get('/', async (req, res) => {
  try {
    const members = await TeamMember.findAll({ order: [['createdAt', 'DESC']] });
    res.json(members);
  } catch (error) {
    res.status(500).json({ message: 'Failed to fetch team members' });
  }
});

// ❌ Delete a member
router.delete('/:id', async (req, res) => {
  try {
    const member = await TeamMember.findByPk(req.params.id);
    if (!member) return res.status(404).json({ message: 'Member not found' });

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

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

module.exports = router;
