const settingsDb = require('./settings.db')

// Keys safe to expose on the public site.
const PUBLIC_KEYS = [
  'site_mode',
  'maintenance_message',
  'status_message',
  'homepage_teaser',
  'contact_email',
  'site_title',
  'hero_layout', // portal hero composition (JSON). Draft key stays admin-only.
]

async function get(key) {
  return settingsDb.get(key)
}

async function set(key, value, updatedBy = null) {
  return settingsDb.set(key, value, updatedBy)
}

async function setMany(obj, updatedBy = null) {
  for (const [key, value] of Object.entries(obj)) {
    await settingsDb.set(key, value, updatedBy)
  }
}

async function getAll() {
  const rows = await settingsDb.getAll()
  return rows.reduce((acc, row) => {
    acc[row.key] = row.value
    return acc
  }, {})
}

async function getPublic() {
  const all = await getAll()
  return PUBLIC_KEYS.reduce((acc, key) => {
    if (all[key] !== undefined) acc[key] = all[key]
    return acc
  }, {})
}

module.exports = { get, set, setMany, getAll, getPublic, PUBLIC_KEYS }
