// Enabled-plugin gating for the router. Fetches the enabled plugin-name list
// ONCE (cached promise) so a disabled backend plugin's frontend routes become
// unreachable by direct URL. Fail-open: any fetch error treats every plugin as
// enabled, so an API blip can never brick navigation.
import { pluginsApi } from '../api'

let enabledPromise = null
let enabledSet = null // resolved Set<string>, or null while pending / on failure

// Kick off (or reuse) the single fetch. The endpoint is jwt-optional so this
// works on unauthenticated kiosk routes (e.g. /tv) too.
export function loadEnabledPlugins() {
  if (!enabledPromise) {
    enabledPromise = pluginsApi.enabled()
      .then(response => {
        const names = response?.data?.data
        // Only trust a real array; anything else -> fail open (null).
        enabledSet = Array.isArray(names) ? new Set(names) : null
        return enabledSet
      })
      .catch(() => {
        // Fail open: leave enabledSet null so isPluginEnabled returns true.
        enabledSet = null
        return null
      })
  }
  return enabledPromise
}

// True if the plugin is enabled OR the list is unknown (fail-open). A null
// enabledSet means we never got a trustworthy answer, so allow everything.
export function isPluginEnabled(name) {
  if (!name) return true
  if (enabledSet === null) return true
  return enabledSet.has(name)
}

// Test/hot-reload hook: forget the cached result so the next call refetches.
export function resetEnabledPlugins() {
  enabledPromise = null
  enabledSet = null
}
