// Branding for the Discord bot. Mirrors the server's BRAND_* scheme so embeds and
// logs carry the instance identity. Kept minimal — the bot only needs the name
// and the accent color (as an int for discord.js embeds).
//
// The accent additionally tracks ADMIN THEMING. An admin who re-themes the site
// changes `theme_visual`, which the server resolves into the effective
// `brand.accent` on GET /public/settings (docs/website/THEMING_AND_NAV.md
// §4.5). This process boots from env and then follows that value, so embeds
// don't stay the old color until someone restarts the container.
//
// Design constraints this satisfies:
//   • env is always a working answer — a site that is down, unconfigured or
//     mid-restart never costs the bot its accent, it just keeps the last known
//     good one;
//   • reading `brand.accentInt` never awaits and never throws, because it is
//     read inline while building an embed;
//   • at most one refresh is ever in flight.
require('dotenv').config()

const siteApi = require('./site/siteApiClient')
const createLogger = require('./utils/logger')

const log = createLogger('brand')

const name = process.env.BRAND_NAME || 'Runic Gateway'
const ENV_ACCENT = process.env.BRAND_ACCENT_COLOR || '#7f99bd'

function toInt(hex) {
  const n = parseInt(String(hex).replace('#', ''), 16)
  return Number.isNaN(n) ? 0x7f99bd : n
}

// How long a fetched accent is trusted before the next read triggers a refresh.
// A theme change reaching Discord within ten minutes is fine; a network call per
// embed is not.
const TTL_MS = 10 * 60 * 1000

let accentHex = ENV_ACCENT
let accentInt = toInt(ENV_ACCENT)
let fetchedAt = 0
let inFlight = null

async function fetchAccent() {
  const res = await siteApi.getPublicSettings()
  // Any failure — site down, maintenance, malformed body — leaves the current
  // value in place. Stamping fetchedAt regardless is deliberate: it stops a
  // persistently unreachable site from firing a request on every single read.
  fetchedAt = Date.now()
  const accent = res.ok ? res.data?.brand?.accent : null
  if (typeof accent !== 'string' || !/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(accent)) return
  if (accent === accentHex) return
  accentHex = accent
  accentInt = toInt(accent)
  log.info('embed accent updated from the site', { accent })
}

// Kick off a refresh if the cached value is stale. Never awaited by a reader —
// the current value is returned immediately and the next read sees the new one.
function refreshIfStale() {
  if (inFlight || Date.now() - fetchedAt < TTL_MS) return inFlight
  inFlight = fetchAccent()
    .catch((err) => log.warn('accent refresh failed — keeping the current value', { message: err.message }))
    .finally(() => {
      inFlight = null
    })
  return inFlight
}

module.exports = {
  name,
  // Getters, not values: consumers already read `brand.accentInt` inline when
  // building an embed, so this keeps the accent current with no call-site change.
  get accentHex() {
    refreshIfStale()
    return accentHex
  },
  get accentInt() {
    refreshIfStale()
    return accentInt
  },
  // Awaited once at startup so the first embed of a process is already correct.
  refreshAccent: () => refreshIfStale() || Promise.resolve(),
}
