/**
 * Static third-party terms that travel with every contract package (Anlage 2b/2c):
 * ADSp 2017 and Logistik-AGB 2019. The PDFs are bundled as Nitro server assets
 * (server/assets/offers/*.pdf — same mechanism as the brand logos) so they are
 * available in the production bundle without touching the filesystem layout.
 * Sources: reference/contracts/ (tracked copies).
 */
export interface StaticAnnex {
  key: 'adsp' | 'logistikagb'
  asset: string
  filename: string
  title: { de: string; en: string }
}

export const STATIC_ANNEXES: StaticAnnex[] = [
  { key: 'adsp', asset: 'offers/DSLV-ADSp-2017.pdf', filename: 'ADSp-2017_DSLV.pdf', title: { de: 'Anlage 2b – ADSp 2017', en: 'Annex 2b – ADSp 2017' } },
  { key: 'logistikagb', asset: 'offers/Logistik-AGB_2019_dt.pdf', filename: 'Logistik-AGB-2019.pdf', title: { de: 'Anlage 2c – Logistik-AGB 2019', en: 'Annex 2c – Logistik-AGB 2019' } }
]

const cache: Record<string, Buffer | null> = {}

export const loadStaticAnnex = async (key: string): Promise<{ buffer: Buffer; filename: string; title: { de: string; en: string } } | null> => {
  const def = STATIC_ANNEXES.find((a) => a.key === key)
  if (!def) return null
  if (!(key in cache)) {
    try {
      const storage = useStorage('assets:server')
      const raw: any = await storage.getItemRaw(def.asset)
      cache[key] = raw ? (Buffer.isBuffer(raw) ? raw : Buffer.from(raw)) : null
    } catch (err: any) {
      console.warn('[Offers] static annex not loadable:', def.asset, err?.message || err)
      cache[key] = null
    }
  }
  const buffer = cache[key]
  return buffer ? { buffer, filename: def.filename, title: def.title } : null
}
