/**
 * Carrier logos (DHL / DPD) for the price-sheet PDF — PNGs from public/assets/shipper, bundled as the
 * Nitro server asset `assets:shipper` (nuxt.config serverAssets, same mechanism as the flags).
 * Returned as data URLs; pdfmake scales them with `fit`. Missing file → no logo, the name is printed.
 */
import { CARRIER_LOGO_PATHS, carrierCodeOf } from '../../../app/utils/shippingPriceSheet'

export interface CarrierLogo { dataUrl: string }
const cache = new Map<string, CarrierLogo | null>()

export const loadCarrierLogo = async (name: string | null | undefined): Promise<CarrierLogo | null> => {
  const code = carrierCodeOf(name, name || '')
  const file = CARRIER_LOGO_PATHS[code]?.png
  if (!file) return null
  if (cache.has(code)) return cache.get(code) || null
  let logo: CarrierLogo | null = null
  try {
    const storage = useStorage('assets:shipper')
    const raw: any = await storage.getItemRaw(file)
    const buf = raw ? (Buffer.isBuffer(raw) ? raw : Buffer.from(raw)) : null
    if (buf && buf.length) logo = { dataUrl: `data:image/png;base64,${buf.toString('base64')}` }
  } catch (err: any) {
    console.warn('[carrierLogos] logo not loaded:', code, err?.message || err)
  }
  cache.set(code, logo)
  return logo
}

export const loadCarrierLogos = async (names: (string | null | undefined)[]): Promise<Record<string, CarrierLogo>> => {
  const out: Record<string, CarrierLogo> = {}
  for (const n of [...new Set(names.map((x) => carrierCodeOf(x, x || '')))]) {
    const l = await loadCarrierLogo(n)
    if (l) out[n] = l
  }
  return out
}
