// Tiny fetch wrapper for calling the bot process's /internal/* API (shared
// secret, same pattern as requireInternalKey on both sides). Used by the
// Discord Bot admin controller to push config after a save and to poll live
// status for the admin panel. Never throws — callers get { ok: false, error }
// on any failure (bot unreachable, timeout, non-2xx) so an admin save/poll
// never 500s just because the bot container is down or restarting.
const log = require('./logger')('bot-internal-client')

const BASE_URL = process.env.BOT_INTERNAL_URL || 'http://localhost:4100'
const KEY = process.env.BOT_INTERNAL_KEY || ''
const TIMEOUT_MS = 4000

async function call(path, { method = 'GET', body } = {}) {
  const controller = new AbortController()
  const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS)
  try {
    const res = await fetch(`${BASE_URL}${path}`, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'X-Internal-Key': KEY,
      },
      body: body ? JSON.stringify(body) : undefined,
      signal: controller.signal,
    })
    if (!res.ok) {
      // Include the numeric status + parsed body (if any) so callers — e.g. the
      // announcement worker — can distinguish 503 (bot down, retry) from a config
      // error. Non-JSON bodies just leave `data` null.
      let data = null
      try {
        data = await res.json()
      } catch {
        // ignore — body already reported via status
      }
      return { ok: false, status: res.status, data, error: `bot responded ${res.status}` }
    }
    return { ok: true, status: res.status, data: await res.json() }
  } catch (err) {
    log.warn('bot internal call failed', { path, message: err.message })
    return { ok: false, status: 0, error: err.message }
  } finally {
    clearTimeout(timeout)
  }
}

// Push a config change (start/stop the bot's Discord client).
function pushConfig({ token, guildId, enabled }) {
  return call('/internal/config', { method: 'POST', body: { token, guildId, enabled } })
}

// Live connection status, for the admin panel.
function getStatus() {
  return call('/internal/status')
}

// Site -> bot: a news post was published, post it to the configured #news
// channel. Fire-and-forget from the caller's perspective — never throws, so
// a bot outage never breaks publishing a post.
function announce({ title, excerpt, url, imageUrl }) {
  return call('/internal/announce', { method: 'POST', body: { title, excerpt, url, imageUrl } })
}

// Site -> bot: an approved appeal wants the underlying Discord action reversed
// (unban for a 'ban', clear the timeout for a 'mute'). Best-effort like every
// call here — never throws, so an approved appeal still resolves when the bot is
// down (the caller records reversal_status='failed' from `ok:false`).
function reverseModAction({ discordUserId, actionType, appealId }) {
  return call('/internal/mod-reverse', {
    method: 'POST',
    body: { discord_user_id: discordUserId, action_type: actionType, appeal_id: appealId },
  })
}

module.exports = { pushConfig, getStatus, announce, reverseModAction }
