// Per-guild key/value config the bot owns (see guild_config in
// server/db/schema.sql). Generic get/set now; filters/schedules/role-menu
// config reuses this same table in later phases.
const db = require('../db')

const MOD_LOG_CHANNEL_KEY = 'mod_log_channel_id'
const AUTO_ROLE_KEY = 'auto_role_id'
const INVITE_CHANNEL_KEY = 'invite_channel_id'
const NEWS_CHANNEL_KEY = 'news_channel_id'

async function get(guildId, key) {
  const rows = await db.query('SELECT value FROM guild_config WHERE guild_id = ? AND `key` = ? LIMIT 1', [guildId, key])
  return rows[0] ? rows[0].value : null
}

async function set(guildId, key, value) {
  await db.query(
    `INSERT INTO guild_config (guild_id, \`key\`, value) VALUES (?, ?, ?)
     ON DUPLICATE KEY UPDATE value = VALUES(value)`,
    [guildId, key, value],
  )
}

const getModLogChannelId = (guildId) => get(guildId, MOD_LOG_CHANNEL_KEY)
const setModLogChannelId = (guildId, channelId) => set(guildId, MOD_LOG_CHANNEL_KEY, channelId)

const getAutoRoleId = (guildId) => get(guildId, AUTO_ROLE_KEY)
const setAutoRoleId = (guildId, roleId) => set(guildId, AUTO_ROLE_KEY, roleId)

const getInviteChannelId = (guildId) => get(guildId, INVITE_CHANNEL_KEY)
const setInviteChannelId = (guildId, channelId) => set(guildId, INVITE_CHANNEL_KEY, channelId)

const getNewsChannelId = (guildId) => get(guildId, NEWS_CHANNEL_KEY)
const setNewsChannelId = (guildId, channelId) => set(guildId, NEWS_CHANNEL_KEY, channelId)

module.exports = {
  get,
  set,
  getModLogChannelId,
  setModLogChannelId,
  getAutoRoleId,
  setAutoRoleId,
  getInviteChannelId,
  setInviteChannelId,
  getNewsChannelId,
  setNewsChannelId,
}
