import express from 'express';
import Department from '../models/Department.js';
import Employee from '../models/Employee.js';
import { protect } from '../middleware/auth.js';

const router = express.Router();
router.use(protect);

router.get('/', async (req, res, next) => {
  try {
    const departments = await Department.find().sort({ name: 1 });
    const withCounts = await Promise.all(
      departments.map(async (d) => {
        const count = await Employee.countDocuments({ department: d._id, status: 'active' });
        return { ...d.toObject(), employeeCount: count };
      })
    );
    res.json(withCounts);
  } catch (err) {
    next(err);
  }
});

router.post('/', async (req, res, next) => {
  try {
    const dept = await Department.create(req.body);
    res.status(201).json(dept);
  } catch (err) {
    next(err);
  }
});

router.put('/:id', async (req, res, next) => {
  try {
    const dept = await Department.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
      runValidators: true,
    });
    if (!dept) return res.status(404).json({ message: 'Department not found' });
    res.json(dept);
  } catch (err) {
    next(err);
  }
});

router.delete('/:id', async (req, res, next) => {
  try {
    const count = await Employee.countDocuments({ department: req.params.id });
    if (count > 0) {
      return res.status(400).json({ message: 'Cannot delete department with employees' });
    }
    await Department.findByIdAndDelete(req.params.id);
    res.json({ message: 'Deleted' });
  } catch (err) {
    next(err);
  }
});

export default router;
