// app/utils/strapi.js

export function getStrapiBaseUrl(event) {
  // En server/Nitro, on récupère runtimeConfig via l'event si dispo,
  // sinon on retombe sur la variable d'env publique.
  const base =
    event?.context?.runtimeConfig?.public?.strapiUrl ||
    process.env.NUXT_PUBLIC_STRAPI_URL

  if (!base) {
    throw new Error("Missing runtimeConfig.public.strapiUrl (NUXT_PUBLIC_STRAPI_URL)")
  }

  try {
    new URL(base)
  } catch {
    throw new Error(`Invalid Strapi base URL: ${base}`)
  }

  return base.replace(/\/$/, "")
}

export async function strapiFetch(event, path, options = {}) {
  const base = getStrapiBaseUrl(event)
  const url = `${base}${path.startsWith("/") ? path : `/${path}`}`

  return await $fetch(url, {
    ...options,
    headers: {
      ...(options.headers || {}),
    },
  })
}
