'use strict'

const { execute, queryOne, query } = require('../database/postgres')

class PluginConfigStore {
  constructor(pluginId) {
    this.pluginId = pluginId
  }

  async get(key) {
    const row = await queryOne(
      'SELECT value FROM plugin_configs WHERE plugin_id = $1 AND key = $2',
      [this.pluginId, key]
    )
    return row ? row.value : null
  }

  async set(key, value) {
    const val = value === null ? null : String(value)
    await execute(
      `INSERT INTO plugin_configs (plugin_id, key, value) VALUES ($1, $2, $3)
       ON CONFLICT (plugin_id, key) DO UPDATE SET value = EXCLUDED.value`,
      [this.pluginId, key, val]
    )
  }

  async getAll() {
    const rows = await query(
      'SELECT key, value FROM plugin_configs WHERE plugin_id = $1',
      [this.pluginId]
    )
    return Object.fromEntries(rows.map((r) => [r.key, r.value]))
  }

  async delete(key) {
    await execute(
      'DELETE FROM plugin_configs WHERE plugin_id = $1 AND key = $2',
      [this.pluginId, key]
    )
  }
}

module.exports = PluginConfigStore
