const express = require('express');
const { requireCapability } = require('../middleware/auth');
const { bookLedger, createBook, deleteBook, ledgerReport, listBooks, updateBook } = require('../services/books');
const { exportReport } = require('../services/reportExport');

const router = express.Router();

router.get('/books', (req, res) => {
  res.json(listBooks(req.companyId));
});

router.post('/books', requireCapability('finance.manage'), (req, res) => {
  res.status(201).json({ book: createBook(req.body, req.user.id, req.companyId) });
});

router.put('/books/:id', requireCapability('finance.manage'), (req, res) => {
  const book = updateBook(req.params.id, req.body, req.user.id, req.companyId);
  if (!book) return res.status(404).json({ error: 'Book not found' });
  return res.json({ book });
});

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

router.get('/books/:code/ledger', (req, res) => {
  const year = Number(req.query.year) || new Date().getFullYear();
  const ledger = bookLedger(req.params.code, year, req.companyId);
  if (!ledger) return res.status(404).json({ error: 'Book not found' });
  return res.json({ ledger });
});

router.post('/books/:code/ledger/export', async (req, res) => {
  const year = Number(req.body.year) || new Date().getFullYear();
  const report = ledgerReport(req.params.code, year, req.companyId);
  if (!report) return res.status(404).json({ error: 'Book not found' });
  const format = String(req.body.format || 'csv').toLowerCase();
  const output = await exportReport(report, format);
  const extension = { csv: 'csv', xlsx: 'xlsx', pdf: 'pdf' }[format] || 'txt';
  res.setHeader('Content-Type', output.contentType);
  res.setHeader('Content-Disposition', `attachment; filename="deprecore-${req.params.code}-ledger-${year}.${extension}"`);
  return res.send(output.body);
});

module.exports = router;
