const express = require('express');
const { requireCapability } = require('../middleware/auth');
const {
  deleteAdjustment,
  previewDisposal,
  recordAdjustment,
  recordDisposal,
  reverseDisposal
} = require('../services/disposals');

const router = express.Router();

router.post('/assets/:id/disposal/preview', (req, res) => {
  const preview = previewDisposal(req.params.id, req.body);
  if (!preview) return res.status(404).json({ error: 'Asset not found' });
  return res.json({ preview });
});

router.post('/assets/:id/disposals', requireCapability('finance.manage'), (req, res) => {
  const result = recordDisposal(req.params.id, req.body, req.user.id);
  if (!result) return res.status(404).json({ error: 'Asset not found' });
  return res.status(201).json(result);
});

router.delete('/assets/:id/disposals/:disposalId', requireCapability('finance.manage'), (req, res) => {
  const asset = reverseDisposal(req.params.id, req.params.disposalId, req.user.id);
  if (!asset) return res.status(404).json({ error: 'Disposal not found' });
  return res.json({ asset });
});

router.post('/assets/:id/adjustments', requireCapability('finance.manage'), (req, res) => {
  const adjustment = recordAdjustment(req.params.id, req.body, req.user.id);
  if (!adjustment) return res.status(404).json({ error: 'Asset not found' });
  return res.status(201).json({ adjustment });
});

router.delete('/assets/:id/adjustments/:adjustmentId', requireCapability('finance.manage'), (req, res) => {
  if (!deleteAdjustment(req.params.id, req.params.adjustmentId, req.user.id)) {
    return res.status(404).json({ error: 'Adjustment not found' });
  }
  return res.status(204).end();
});

module.exports = router;
