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

const router = express.Router();

router.get('/tax-rules', (req, res) => {
  const ruleSets = all('SELECT * FROM tax_rule_sets ORDER BY active DESC, effective_date DESC, id DESC').map((row) => ({
    ...row,
    active: Boolean(row.active),
    rules_json: parseJson(row.rules_json, {})
  }));
  res.json({ ruleSets });
});

router.post('/tax-rules', requireRole('admin', 'finance'), (req, res) => {
  const result = run(
    'INSERT INTO tax_rule_sets (jurisdiction, name, effective_date, version, rules_json, active, source_note, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
    [
      req.body.jurisdiction,
      req.body.name,
      req.body.effective_date,
      req.body.version,
      JSON.stringify(req.body.rules_json || req.body.rules || {}),
      req.body.active === false ? 0 : 1,
      req.body.source_note || null,
      now()
    ]
  );
  audit(req.user.id, 'create', 'tax_rule_set', result.lastInsertRowid, null, req.body);
  res.status(201).json({ ruleSet: one('SELECT * FROM tax_rule_sets WHERE id = ?', [result.lastInsertRowid]) });
});

module.exports = router;
