// Shared warranty fetch + hero-badge derivation for asset detail pages.
// Pass a getter for the asset id; get back the warranties list (to feed a
// WarrantyPanel) and a heroWarranty for a compact status badge.
import { ref, computed, watch } from 'vue'
import { warrantyApi } from '../api'

const STATUS_RANK = { expired: 0, expiring: 1, active: 2, unknown: 3 }
const STATUS_LABELS = {
  active: 'Under Warranty',
  expiring: 'Warranty Expiring',
  expired: 'Warranty Expired',
  unknown: 'Warranty',
}

export function useWarrantyBadge(getAssetId) {
  const warranties = ref([])

  // Worst-case warranty drives the badge: expired > expiring > active > unknown.
  const heroWarranty = computed(() => {
    if (!warranties.value.length) return null
    const worst = [...warranties.value]
      .sort((a, b) => (STATUS_RANK[a.status] ?? 9) - (STATUS_RANK[b.status] ?? 9))[0]
    return { ...worst, label: STATUS_LABELS[worst.status] || 'Warranty' }
  })

  function warrantyDate(d) {
    return d ? new Date(d + 'T00:00:00').toLocaleDateString() : ''
  }

  async function load() {
    const assetid = getAssetId()
    if (!assetid) { warranties.value = []; return }
    try {
      const response = await warrantyApi.forAsset(assetid)
      warranties.value = response.data.data || []
    } catch (err) {
      warranties.value = []
    }
  }

  watch(getAssetId, load, { immediate: true })

  return { warranties, heroWarranty, warrantyDate, reloadWarranties: load }
}
