const express = require('express');
const { requireCapability } = 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, req.companyId) });
});

router.post('/employees', requireCapability('assets.assign'), (req, res) => {
  res.status(201).json({ employee: upsertEmployee({ ...req.body, source: req.body.source || 'manual' }, req.companyId) });
});

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

router.post('/assignments', requireCapability('assets.assign'), (req, res, next) => {
  try {
    res.status(201).json({ assignment: assignAsset(req.body, req.user.id, req.companyId) });
  } catch (error) {
    next(error);
  }
});

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

module.exports = router;
