const { one, parseJson } = require('../db');

function activeRuleSet() {
  const row = one('SELECT rules_json FROM tax_rule_sets WHERE active = 1 ORDER BY effective_date DESC, id DESC LIMIT 1');
  return row ? parseJson(row.rules_json, {}) : {};
}

// Resolve the depreciation rule set a book should use: its explicitly assigned
// rule set when present, otherwise the globally active set.
function ruleSetForBook(bookCode) {
  if (bookCode) {
    try {
      const book = one('SELECT tax_rule_set_id FROM books WHERE code = ?', [bookCode]);
      if (book && book.tax_rule_set_id) {
        const row = one('SELECT rules_json FROM tax_rule_sets WHERE id = ?', [book.tax_rule_set_id]);
        if (row) return parseJson(row.rules_json, {});
      }
    } catch {
      // books table may not exist on a very old database; fall through to active set
    }
  }
  return activeRuleSet();
}

module.exports = { activeRuleSet, ruleSetForBook };
