const express = require('express');
const { requireRole } = require('../middleware/auth');
const {
  assignAsset,
  assignmentRows,
  assignmentSummary,
  listEmployees,
  releaseAssignment,
  upsertEmployee
} = require('../services/assignments');

const router = express.Router();

router.get('/employees', (req, res) => {
  res.json({ employees: listEmployees(req.query) });
});

router.post('/employees', requireRole('admin', 'finance', 'operations'), (req, res) => {
  res.status(201).json({ employee: upsertEmployee({ ...req.body, source: req.body.source || 'manual' }) });
});

router.get('/assignments', (req, res) => {
  res.json({
    summary: assignmentSummary(),
    assignments: assignmentRows({
      asset_id: req.query.asset_id || null,
      employee_id: req.query.employee_id || null,
      active: req.query.active === 'true'
    })
  });
});

router.post('/assignments', requireRole('admin', 'finance', 'operations'), (req, res, next) => {
  try {
    res.status(201).json({ assignment: assignAsset(req.body, req.user.id) });
  } catch (error) {
    next(error);
  }
});

router.put('/assignments/:id/release', requireRole('admin', 'finance', 'operations'), (req, res) => {
  const assignment = releaseAssignment(req.params.id, req.body, req.user.id);
  if (!assignment) return res.status(404).json({ error: 'Assignment not found' });
  return res.json({ assignment });
});

module.exports = router;
