import { env } from "fastly:env";

async function handleRequest(event) {
  // This variable is not defined in Fiddle but you see the possible values here: https://developer.fastly.com/reference/compute/ecp-env/fastly-region/
  const fastly_region = env("FASTLY_REGION");

  // We do not have backend health support in the JS SDK at time of writing so the backend selection is based on region alone
  let backend = "origin_0"; /* Default to European origin */
  if (/(^EU-|^AF-|^South-Africa$)/.exec(fastly_region)) {
    backend = "origin_0"; /* European origin */
  } else if (/(^Asia-|^Asia$|^APAC$)/.exec(fastly_region)) {
    backend = "origin_1"; /* Asian origin */
  } else if (/(^SA-|^US-|^North-America$)/.exec(fastly_region)) {
    backend = "origin_2"; /* American origin */
  }

  const backendResponse = fetch(event.request, {
    backend: backend
  });

  return backendResponse;
}

addEventListener("fetch", (event) => event.respondWith(handleRequest(event)))