const express = require('express');
const { all, audit, json, now, one, parseJson, run } = require('../db');
const { requireCapability } = require('../middleware/auth');
const {
  depreciationReport,
  monthlyDepreciationReport,
  writeDepreciationPdf
} = require('../services/reports');
const { catalog, runReport } = require('../services/reportEngine');
const { exportReport } = require('../services/reportExport');

const router = express.Router();

const EXPORT_EXTENSIONS = { csv: 'csv', xlsx: 'xlsx', pdf: 'pdf', json: 'json' };

router.get('/reports/catalog', (req, res) => {
  res.json(catalog());
});

router.post('/reports/run', (req, res) => {
  res.json({ report: runReport(req.body.type, { ...(req.body.options || {}), entity_id: req.companyId }) });
});

router.post('/reports/export', async (req, res) => {
  const format = String(req.body.format || 'csv').toLowerCase();
  const report = runReport(req.body.type, { ...(req.body.options || {}), entity_id: req.companyId });
  const output = await exportReport(report, format);
  const extension = EXPORT_EXTENSIONS[format] || 'txt';
  res.setHeader('Content-Type', output.contentType);
  res.setHeader('Content-Disposition', `attachment; filename="deprecore-${req.body.type}.${extension}"`);
  res.send(output.body);
});

router.get('/saved-reports', (req, res) => {
  const reports = all(
    `SELECT s.*, u.name AS created_by_name FROM saved_reports s
     LEFT JOIN users u ON u.id = s.created_by WHERE s.entity_id = ? ORDER BY s.name`,
    [req.companyId]
  ).map((row) => ({ ...row, options_json: parseJson(row.options_json, {}) }));
  res.json({ reports });
});

router.post('/saved-reports', requireCapability('reports.save'), (req, res) => {
  const result = run(
    'INSERT INTO saved_reports (entity_id, name, report_type, options_json, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?)',
    [req.companyId, req.body.name || 'Saved report', req.body.report_type, json(req.body.options || {}), req.user.id, now()]
  );
  audit(req.user.id, 'create', 'saved_report', result.lastInsertRowid, null, req.body);
  const saved = one('SELECT * FROM saved_reports WHERE id = ?', [result.lastInsertRowid]);
  res.status(201).json({ report: { ...saved, options_json: parseJson(saved.options_json, {}) } });
});

router.delete('/saved-reports/:id', requireCapability('reports.save'), (req, res) => {
  const result = run('DELETE FROM saved_reports WHERE id = ? AND entity_id = ?', [req.params.id, req.companyId]);
  if (!result.changes) return res.status(404).json({ error: 'Saved report not found' });
  audit(req.user.id, 'delete', 'saved_report', req.params.id, null, null);
  return res.status(204).end();
});

router.get('/reports/depreciation', (req, res) => {
  const year = Number(req.query.year || new Date().getFullYear());
  const bookType = req.query.book || 'GAAP';
  res.json(depreciationReport(year, bookType, req.companyId));
});

router.get('/reports/monthly-depreciation', (req, res) => {
  const year = Number(req.query.year || new Date().getFullYear());
  const bookType = req.query.book || 'GAAP';
  res.json(monthlyDepreciationReport(year, bookType, req.companyId));
});

router.get('/reports/depreciation.pdf', (req, res) => {
  const year = Number(req.query.year || new Date().getFullYear());
  const book = req.query.book || 'GAAP';
  writeDepreciationPdf(res, year, book, req.companyId);
});

module.exports = router;
