// ── Admin: Discord bot control ─────────────────────────────────────────────
//
// Phase 1: entering/enabling the bot token here (not an env var) and pushing
// it to the bot process over the internal API. SECURITY: the token is
// write-only over this API, same convention as auth provider secrets — it is
// stored encrypted and NEVER returned; responses expose only `hasToken`. A
// blank `token` on save means "leave the existing token unchanged".

const botConfig = require('../../../model/botConfig/botConfig.model')
const botClient = require('../../../utils/botInternalClient')
const activity = require('../../../model/activity/activity.model')

const log = require('../../../utils/logger')('admin')

const SNOWFLAKE = /^\d{17,20}$/

// Confirm a bot token is real by asking Discord who it belongs to. Returns
// true/false only on a definitive answer; returns true (don't block the save)
// if Discord couldn't be reached at all, since a network hiccup shouldn't
// stop an admin from saving a token that may well be valid. Guild-membership
// validation is deliberately NOT done here — a bot token is valid before the
// bot has ever been invited to the guild, so checking guild access here would
// reject perfectly good first-time setups with a false negative.
async function isValidBotToken(token) {
  try {
    const res = await fetch('https://discord.com/api/users/@me', {
      headers: { Authorization: `Bot ${token}` },
    })
    return res.status !== 401
  } catch (err) {
    log.warn('discord token validation unreachable — not blocking save', { message: err.message })
    return true
  }
}

// GET /admin/discord-bot/config — masked config + live status (falls back to
// the last-known DB-mirrored status if the bot process is unreachable).
async function getConfig(req, res) {
  try {
    const config = await botConfig.getSafe()
    const live = await botClient.getStatus()
    if (live.ok) {
      config.status = live.data.status
      config.statusDetail = live.data.statusDetail
      config.lastConnectedAt = live.data.lastConnectedAt
      await botConfig.recordStatus(live.data)
    } else {
      config.statusDetail = config.statusDetail || `bot unreachable: ${live.error}`
    }
    return res.json(config)
  } catch (err) {
    log.error('discordBot.getConfig', err)
    return res.status(500).json({ message: 'Internal Server Error' })
  }
}

// PUT /admin/discord-bot/config — save + push to the bot process.
async function saveConfig(req, res) {
  const { guildId, token, enabled } = req.body
  try {
    if (guildId !== undefined && guildId !== '' && !SNOWFLAKE.test(guildId)) {
      return res.status(400).json({ message: 'guildId does not look like a valid Discord server ID.' })
    }

    if (token) {
      const ok = await isValidBotToken(token)
      if (!ok) return res.status(400).json({ message: 'That bot token was rejected by Discord — check it and try again.' })
    }

    const current = await botConfig.getSafe()
    const willHaveToken = Boolean(token) || current.hasToken
    if (enabled && !willHaveToken) {
      return res.status(400).json({ message: 'A bot token is required before enabling.' })
    }

    const saved = await botConfig.save({ guildId, token, enabled, updatedBy: req.user.id })
    const withToken = await botConfig.getWithToken()
    const push = await botClient.pushConfig({ token: withToken.token, guildId: saved.guildId, enabled: saved.enabled })
    if (push.ok) {
      await botConfig.recordStatus(push.data)
      saved.status = push.data.status
      saved.statusDetail = push.data.statusDetail
      saved.lastConnectedAt = push.data.lastConnectedAt
    } else {
      saved.statusDetail = `bot unreachable: ${push.error}`
    }

    await activity.log({ req, action: 'discordBot.config.update', detail: { guildId: saved.guildId, enabled: saved.enabled } })
    log.info('discord bot config updated', { by: req.user.username, enabled: saved.enabled })
    return res.json(saved)
  } catch (err) {
    log.error('discordBot.saveConfig', err)
    return res.status(500).json({ message: 'Internal Server Error' })
  }
}

module.exports = { getConfig, saveConfig }
