// Single source of truth for asset-type display labels + detail routing.
// The map and shopfloor views used to each hardcode these identical maps.
// Keys are lowercase; both 'network_device' and 'network device' are accepted
// because the API sends the underscore form and some map data the spaced form.

const ASSET_TYPE_LABELS = {
  'machine': 'Machines',
  'computer': 'Computers',
  'printer': 'Printers',
  'network_device': 'Network Devices',
  'network device': 'Network Devices',
  'measuring_tool': 'Measuring Tools',
}

const ASSET_TYPE_ROUTES = {
  'machine': '/machines',
  'computer': '/pcs',
  'printer': '/printers',
  'network_device': '/network',
  'network device': '/network',
  'measuring_tool': '/measuringtools',
}

// Plugin-specific id field inside asset.typedata for each asset type.
const ASSET_TYPE_ID_KEYS = {
  'machine': 'machineid',
  'computer': 'computerid',
  'printer': 'printerid',
  'network_device': 'networkdeviceid',
  'network device': 'networkdeviceid',
  'measuring_tool': 'measuringtoolid',
}

function titleCase(text) {
  return String(text || '')
    .replace(/[_-]+/g, ' ')
    .replace(/\b\w/g, c => c.toUpperCase())
}

// Plural, human-friendly label for an asset type. Falls back to title-cased
// input so an unknown/new type still reads sensibly.
export function assetTypeLabel(type) {
  if (!type) return type
  return ASSET_TYPE_LABELS[String(type).toLowerCase()] || titleCase(type)
}

// Base list route for an asset type (e.g. 'computer' -> '/pcs').
export function assetTypeRoute(type) {
  return ASSET_TYPE_ROUTES[String(type || '').toLowerCase()] || '/machines'
}

// Full detail route for a unified-format asset, preferring the plugin-specific
// id in typedata and falling back to the asset id.
export function assetDetailRoute(asset) {
  const type = (asset.assettype || '').toLowerCase()
  const base = assetTypeRoute(type)
  const idKey = ASSET_TYPE_ID_KEYS[type]
  let id = asset.assetid
  if (asset.typedata && idKey && asset.typedata[idKey]) {
    id = asset.typedata[idKey]
  }
  return `${base}/${id}`
}
