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

// Factory for the singleton config tables (bot_config, email_config,
// uo_link_config). Each is a one-row table keyed on id = 1: `get()` returns the
// row (or null before the admin first saves it), and `upsert()` writes only the
// columns the model prepared, leaving the rest untouched. The three tables share
// this shape exactly, so the DB layer is generated rather than copy-pasted —
// only the table name and column list differ.
//
// `fields` are already prepared by the model (secrets pre-encrypted); ordering
// and encryption stay a model-layer concern.
function singletonConfigDb(table, cols) {
  async function get() {
    const rows = await query(`SELECT ${cols} FROM ${table} WHERE id = 1 LIMIT 1`)
    return rows[0] || null
  }

  async function upsert(fields) {
    const columns = Object.keys(fields)
    const vals = columns.map((c) => fields[c])
    const insertCols = ['id', ...columns].map((c) => `\`${c}\``).join(', ')
    const placeholders = ['1', ...columns.map(() => '?')].join(', ')
    const updates = columns.map((c) => `\`${c}\` = VALUES(\`${c}\`)`).join(', ')
    await query(
      `INSERT INTO ${table} (${insertCols}) VALUES (${placeholders})
       ON DUPLICATE KEY UPDATE ${updates}`,
      vals,
    )
    return get()
  }

  return { get, upsert }
}

module.exports = singletonConfigDb
