const express = require('express');
const multer = require('multer');
const { requireCapability } = require('../middleware/auth');
const { bookLedger, createBook, deleteBook, ledgerReport, listBooks, updateBook } = require('../services/books');
const { exportReport } = require('../services/reportExport');
const { rowsFromImport, extensionForUpload } = require('../services/importExport');
const glEntries = require('../services/glEntries');
const glAccounts = require('../services/glAccounts');
const section179Limitation = require('../services/section179Limitation');

const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 16 * 1024 * 1024 } });
const router = express.Router();
const ledgerReader = requireCapability('finance.view');
const ledgerEditor = requireCapability('finance.manage');

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);
});

// ---- GL chart of accounts + posting defaults (full audit) -------------------

router.get('/gl-accounts', ledgerReader, (req, res) => {
  res.json({ accounts: glAccounts.listAccounts(req.companyId), defaults: glAccounts.getDefaults(req.companyId) });
});

router.post('/gl-accounts', ledgerEditor, (req, res, next) => {
  try {
    res.status(201).json({ account: glAccounts.createAccount(req.body, req.user.id, req.companyId) });
  } catch (error) {
    next(error);
  }
});

router.put('/gl-accounts/:id', ledgerEditor, (req, res, next) => {
  try {
    const account = glAccounts.updateAccount(req.params.id, req.body, req.user.id, req.companyId);
    if (!account) return res.status(404).json({ error: 'GL account not found' });
    return res.json({ account });
  } catch (error) {
    return next(error);
  }
});

router.delete('/gl-accounts/:id', ledgerEditor, (req, res) => {
  if (!glAccounts.deleteAccount(req.params.id, req.user.id, req.companyId)) return res.status(404).json({ error: 'GL account not found' });
  return res.status(204).end();
});

// §179 return-level taxable-income limitation + carryover (per company + book + year).
router.get('/section-179/limitation', ledgerReader, (req, res) => {
  const book = req.query.book || 'FEDERAL';
  const year = Number(req.query.year) || new Date().getFullYear();
  res.json({ summary: section179Limitation.summary(req.companyId, book, year, req.query.taxable_income) });
});

router.put('/section-179/limitation', ledgerEditor, (req, res) => {
  const book = req.body.book || 'FEDERAL';
  const year = Number(req.body.year) || new Date().getFullYear();
  res.json({ summary: section179Limitation.save(req.companyId, book, year, req.body.taxable_income, req.user.id) });
});

// GL posting defaults (the fallback accounts the ledgers post to).
router.get('/gl-account-defaults', ledgerReader, (req, res) => {
  res.json({ defaults: glAccounts.getDefaults(req.companyId) });
});

router.put('/gl-account-defaults', ledgerEditor, (req, res) => {
  res.json({ defaults: glAccounts.saveDefaults(req.body, req.user.id, req.companyId) });
});

// ---- GL journal entries (stored, editable; full audit) ----------------------

function glFilters(query, code) {
  return { book: code, year: query.year ? Number(query.year) : null, account: query.account || null, search: query.search || null };
}

router.get('/books/:code/gl-entries', ledgerReader, (req, res) => {
  res.json(glEntries.listEntries(glFilters(req.query, req.params.code), req.companyId));
});

router.post('/books/:code/gl-entries', ledgerEditor, (req, res, next) => {
  try {
    res.status(201).json({ entry: glEntries.createEntry(req.params.code, req.body, req.user.id, req.companyId) });
  } catch (error) {
    next(error);
  }
});

router.put('/books/:code/gl-entries/:id', ledgerEditor, (req, res, next) => {
  try {
    const entry = glEntries.updateEntry(req.params.id, req.body, req.user.id, req.companyId);
    if (!entry) return res.status(404).json({ error: 'GL entry not found' });
    return res.json({ entry });
  } catch (error) {
    return next(error);
  }
});

router.delete('/books/:code/gl-entries/:id', ledgerEditor, (req, res) => {
  if (!glEntries.deleteEntry(req.params.id, req.user.id, req.companyId)) return res.status(404).json({ error: 'GL entry not found' });
  return res.status(204).end();
});

// Per-entry change timeline (from the audit log).
router.get('/books/:code/gl-entries/:id/history', ledgerReader, (req, res) => {
  const history = glEntries.entryHistory(req.params.id, req.companyId);
  if (!history) return res.status(404).json({ error: 'GL entry not found' });
  return res.json({ history });
});

// Dry-run: parse the uploaded CSV/Excel and classify each row (new/update/duplicate/error).
router.post('/books/:code/gl-entries/import/preview', ledgerEditor, upload.single('file'), async (req, res, next) => {
  try {
    if (!req.file) return res.status(400).json({ error: 'File is required' });
    const rows = await rowsFromImport(extensionForUpload(req.file.originalname), req.file.buffer);
    res.json(glEntries.previewImport(rows, req.params.code, req.companyId));
  } catch (error) {
    return next(error);
  }
});

// Commit the classified rows from the preview using the chosen conflict strategy.
router.post('/books/:code/gl-entries/import/commit', ledgerEditor, (req, res, next) => {
  try {
    res.json(glEntries.commitImport(req.body.rows || [], req.body.strategy, req.params.code, req.user.id, req.companyId));
  } catch (error) {
    return next(error);
  }
});

router.get('/books/:code/gl-entries/export', ledgerReader, async (req, res) => {
  const report = glEntries.entriesReport(glFilters(req.query, req.params.code), req.companyId);
  const format = ['csv', 'xlsx'].includes(String(req.query.format).toLowerCase()) ? String(req.query.format).toLowerCase() : 'csv';
  const output = await exportReport(report, format);
  res.setHeader('Content-Type', output.contentType);
  res.setHeader('Content-Disposition', `attachment; filename="deprecore-${req.params.code}-gl-entries.${format}"`);
  return res.send(output.body);
});

module.exports = router;
