// Shared read-through for public site settings (site_base_url, facility_name).
// The settings GET is public (jwt optional), so the kiosk dashboard and the
// print views can read these without auth. Fetched once and cached per page.
import { settingsApi } from '@/api'

let settingsCache = null

async function loadSettings() {
  if (settingsCache) return settingsCache
  try {
    const response = await settingsApi.list()
    const items = response.data?.data || response.data || []
    settingsCache = {}
    for (const s of items) settingsCache[s.key] = s.value
  } catch (err) {
    console.error('Error loading site settings:', err)
    settingsCache = {}
  }
  return settingsCache
}

export async function getSetting(key, fallback = '') {
  const settings = await loadSettings()
  const value = settings[key]
  return (value === undefined || value === null || value === '') ? fallback : value
}

// Public base URL for QR codes / absolute links. Falls back to the current
// browsing origin when a site has not set one.
export async function getSiteBaseUrl() {
  return getSetting('site_base_url', window.location.origin)
}

// Facility name shown on the shopfloor dashboard.
export async function getFacilityName() {
  return getSetting('facility_name', 'West Jefferson')
}
