// Per-type enable/disable flags for optional asset identifiers, read from the
// settings table. Keys follow identifier_<name>_<assettype>_enabled. A legacy
// global key identifier_<name>_enabled is honored as a fallback for older
// installs. Missing = enabled, so a fresh install shows every identifier.
import { reactive } from 'vue'
import { settingsApi } from '../api'

// scope[name][assettype] = boolean. legacy[name] = boolean (old global flag).
const state = reactive({
  scope: {},
  legacy: {},
  loaded: false
})

let inflight = null

const KEY_RE = /^identifier_(.+?)(?:_(machine|computer|printer|network_device|measuring_tool))?_enabled$/

function applySetting(key, value) {
  const match = KEY_RE.exec(key)
  if (!match) return
  const name = match[1]
  const assettype = match[2]
  if (assettype) {
    if (!state.scope[name]) state.scope[name] = {}
    state.scope[name][assettype] = value !== false
  } else {
    state.legacy[name] = value !== false
  }
}

function fetchFlags() {
  inflight = settingsApi.list()
    .then(({ data }) => {
      ;(data.data || []).forEach(s => applySetting(s.key, s.value))
      state.loaded = true
    })
    .catch(() => { state.loaded = true })
    .finally(() => { inflight = null })
  return inflight
}

function loadFlags() {
  if (!state.loaded && !inflight) fetchFlags()
}

// Re-read flags from the server. Call after an identifier setting changes so
// other open views pick it up without a full page reload.
export function reloadIdentifierFlags() {
  return fetchFlags()
}

// Optimistically update one flag in the shared state (e.g. right after a
// Settings toggle) so dependent views react immediately.
export function setIdentifierFlag(name, assettype, enabled) {
  applySetting(`identifier_${name}_${assettype}_enabled`, enabled)
}

// True when identifier `name` should show on `assettype`. Per-type flag wins,
// then the legacy global flag, then default-on.
function isEnabled(name, assettype) {
  const perType = state.scope[name]
  if (perType && assettype in perType) return perType[assettype]
  if (name in state.legacy) return state.legacy[name]
  return true
}

export function useIdentifierFlags() {
  loadFlags()
  return { state, isEnabled }
}
