/**
 * GET /api/materials/warehouse-layouts/meta/img?u=<encoded url> — same-origin relay for Strapi product images so the
 * WebGL renderer can use them as textures (cross-origin images without CORS headers are rejected by WebGL).
 * Only URLs under config.public.strapi are accepted; they are fetched via the INTERNAL Strapi base
 * (config.api.strapi without /api — like products/copy-image.post.ts; the public `/files-api/` alias is Strapi's
 * `/uploads/` there) with the public host as fallback.
 * Browser-cached for a day.
 */
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const u = String(getQuery(event).u || '')
  const publicBase = String(config.public.strapi || '').replace(/\/$/, '')
  if (!u || !publicBase || !u.startsWith(publicBase)) { setResponseStatus(event, 400); return 'invalid url' }
  const internalBase = String((config as any).api?.strapi || '').replace(/\/api\/?$/, '').replace(/\/$/, '')
  const internal = internalBase && internalBase !== publicBase ? u.replace(publicBase, internalBase).replace(internalBase + '/files-api/', internalBase + '/uploads/') : ''
  const candidates = [internal, u].filter(Boolean)
  let lastErr = ''
  for (const url of candidates) {
    try {
      const res = await fetch(url)
      if (!res.ok) { lastErr = 'upstream ' + res.status; continue }
      const buf = Buffer.from(await res.arrayBuffer())
      setHeader(event, 'Content-Type', res.headers.get('content-type') || 'image/jpeg')
      setHeader(event, 'Cache-Control', 'private, max-age=86400')
      return buf
    } catch (e: any) { lastErr = e?.cause?.code || e?.message || 'fetch failed' }
  }
  setResponseStatus(event, 502)
  return 'image relay failed: ' + lastErr
})
