// Shared QR target resolution for printed labels. Each label surface has a
// qr_target_<domain> setting: blank means the QR links to the asset's own
// detail page on this instance; a non-blank value is treated as a URL
// template and every {placeholder} is substituted from the tokens map.
import { getSetting, getSiteBaseUrl } from './siteSettings'

// Substitute {name} placeholders. Values are URL-encoded; unknown or empty
// placeholders collapse to an empty string rather than leaking the braces.
export function fillUrlTemplate(template, tokens) {
  return template.replace(/\{([a-z0-9_]+)\}/gi, (match, name) => {
    const value = tokens[name]
    return (value === undefined || value === null) ? '' : encodeURIComponent(String(value))
  })
}

// Resolve the QR URL for one asset. settingKey is the qr_target_<domain>
// setting, defaultPath the in-app detail route (e.g. /printers/12), tokens
// the placeholder values available to a custom template.
export async function buildQrUrl(settingKey, defaultPath, tokens = {}) {
  const template = (await getSetting(settingKey, '')).trim()
  if (!template) {
    const baseUrl = await getSiteBaseUrl()
    return `${baseUrl}${defaultPath}`
  }
  return fillUrlTemplate(template, tokens)
}
