const db = require('../db/db');

/* ── GET /api/settings/sims ─────────────────────────────────────────────── */
function getSimSettings(req, res) {
  const rows = db.prepare(`SELECT key, value FROM app_settings WHERE key IN ('sim_module_disabled','sim_disabled_ids')`).all();
  const map = Object.fromEntries(rows.map(r => [r.key, r.value]));
  res.json({
    module_disabled: map['sim_module_disabled'] === '1',
    disabled_ids: JSON.parse(map['sim_disabled_ids'] || '[]'),
  });
}

/* ── PUT /api/settings/sims ─────────────────────────────────────────────── */
function updateSimSettings(req, res) {
  const { module_disabled, disabled_ids } = req.body;

  if (module_disabled !== undefined) {
    db.prepare(`INSERT INTO app_settings (key, value) VALUES ('sim_module_disabled', ?)
                ON CONFLICT(key) DO UPDATE SET value = excluded.value`)
      .run(module_disabled ? '1' : '0');
  }

  if (Array.isArray(disabled_ids)) {
    db.prepare(`INSERT INTO app_settings (key, value) VALUES ('sim_disabled_ids', ?)
                ON CONFLICT(key) DO UPDATE SET value = excluded.value`)
      .run(JSON.stringify(disabled_ids));
  }

  res.json({ ok: true });
}

module.exports = { getSimSettings, updateSimSettings };
