const { query } = require('../lib/db')

/**
 * Get all system settings, parsing JSON values where possible
 * @returns {Promise<Object>} key-value map of settings
 */
async function getAll() {
  const rows = await query('SELECT setting_key, setting_value FROM system_settings', {})
  const settings = {}
  rows.forEach(row => {
    if (typeof row.setting_value === 'string') {
      try {
        settings[row.setting_key] = JSON.parse(row.setting_value)
      } catch (_) {
        settings[row.setting_key] = row.setting_value
      }
    } else {
      settings[row.setting_key] = row.setting_value
    }
  })
  return settings
}

/**
 * Upsert a system setting (REPLACE INTO)
 * @param {string} key - setting_key
 * @param {*} value - will be JSON-stringified
 * @returns {Promise<Array>} query result
 */
async function update(key, value) {
  return query(
    'REPLACE INTO system_settings (setting_key, setting_value) VALUES (:setting_key, :setting_value)',
    { setting_key: key, setting_value: JSON.stringify(value) }
  )
}

module.exports = {
  getAll,
  update
}
