const ALLOWED_IMAGE_HOSTS = new Set(["brunofritsch.cl", "www.brunofritsch.cl"])

export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const rawUrl = typeof query.url === "string" ? query.url : ""

  if (!rawUrl) {
    throw createError({
      statusCode: 400,
      statusMessage: "Falta la URL de la imagen"
    })
  }

  let imageUrl: URL

  try {
    imageUrl = new URL(rawUrl)
  } catch {
    throw createError({
      statusCode: 400,
      statusMessage: "URL de imagen invalida"
    })
  }

  if (!["http:", "https:"].includes(imageUrl.protocol) || !ALLOWED_IMAGE_HOSTS.has(imageUrl.hostname)) {
    throw createError({
      statusCode: 403,
      statusMessage: "Host de imagen no permitido"
    })
  }

  const response = await fetch(imageUrl.toString(), {
    headers: {
      "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36"
    }
  })

  if (!response.ok) {
    throw createError({
      statusCode: response.status,
      statusMessage: `No pude cargar la imagen remota (${response.status})`
    })
  }

  const contentType = response.headers.get("content-type")
  const cacheControl = response.headers.get("cache-control")
  const bytes = Buffer.from(await response.arrayBuffer())

  if (contentType) {
    setHeader(event, "content-type", contentType)
  }

  setHeader(event, "cache-control", cacheControl || "public, max-age=3600")

  return bytes
})
