const express = require('express');
const { all, audit, now, one, parseJson, run } = require('../db');
const { requireRole } = require('../middleware/auth');

const router = express.Router();

router.get('/entities', (req, res) => {
  res.json({ entities: all('SELECT * FROM entities ORDER BY name') });
});

router.post('/entities', requireRole('admin', 'finance'), (req, res) => {
  const created = now();
  const result = run(
    'INSERT INTO entities (name, legal_name, tax_id, fiscal_year_end_month, base_currency, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)',
    [
      req.body.name,
      req.body.legal_name || null,
      req.body.tax_id || null,
      Number(req.body.fiscal_year_end_month || 12),
      req.body.base_currency || 'USD',
      created,
      created
    ]
  );
  audit(req.user.id, 'create', 'entity', result.lastInsertRowid, null, req.body);
  res.status(201).json({ entity: one('SELECT * FROM entities WHERE id = ?', [result.lastInsertRowid]) });
});

router.get('/references', (req, res) => {
  const rows = all('SELECT * FROM reference_values ORDER BY type, name');
  res.json({ references: rows.map((row) => ({ ...row, metadata: parseJson(row.metadata, {}) })) });
});

module.exports = router;
