import { getDb } from './db.js';

export function getConfig(key, defaultValue = null) {
  if (!key) return defaultValue;
  const row = getDb().prepare('SELECT value FROM config WHERE key = ?').get(String(key));
  if (!row) return defaultValue;
  return row.value;
}

export function setConfig(key, value) {
  if (!key) throw new Error('config key is required');
  const stringified = value === null || value === undefined ? '' : String(value);
  getDb().prepare(`
    INSERT INTO config (key, value) VALUES (?, ?)
    ON CONFLICT(key) DO UPDATE SET value = excluded.value
  `).run(String(key), stringified);
  return stringified;
}

export function listConfig() {
  return getDb().prepare('SELECT key, value FROM config ORDER BY key ASC').all();
}

export function deleteConfig(key) {
  if (!key) return 0;
  const info = getDb().prepare('DELETE FROM config WHERE key = ?').run(String(key));
  return info.changes;
}
