const express = require('express');
const { requireCapability } = require('../middleware/auth');
const {
  createLease,
  deleteLease,
  getLease,
  leaseSchedule,
  listLeases,
  updateLease
} = require('../services/leases');

const router = express.Router();

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

router.post('/leases', requireCapability('finance.manage'), (req, res) => {
  res.status(201).json({ lease: createLease(req.body, req.user.id) });
});

router.put('/leases/:id', requireCapability('finance.manage'), (req, res) => {
  const lease = updateLease(req.params.id, req.body, req.user.id);
  if (!lease) return res.status(404).json({ error: 'Lease not found' });
  return res.json({ lease });
});

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

router.get('/leases/:id/schedule', (req, res) => {
  const lease = getLease(req.params.id);
  if (!lease) return res.status(404).json({ error: 'Lease not found' });
  return res.json({ lease, schedule: leaseSchedule(lease) });
});

module.exports = router;
