import { allowDynamicBackends } from "fastly:experimental";
allowDynamicBackends(true);

async function handler(event) {
  const req = event.request;

  let backendResponse = await fetch(req, { backend: 'origin_0', });

  const status = backendResponse.status;
  console.log(`Status Code ${status}`);

  // If response status is a redirect,
  // then perform a fetch to the Location header
  if(status === 301 || status === 302 || status === 307 || status === 308) {
    const location = backendResponse.headers.get('Location');
    if (location == null) {
      throw new Error('Received redirect status, but missing Location header.');
    }

    // Resolve the location in case it's a relative URL
    // if it's relative, resolve it relative to https://http-me.glitch.me
    const locationUrl = String(new URL(location, 'https://http-me.glitch.me/'));

    console.log(`Redirected to ${locationUrl}`);
    backendResponse = await fetch(locationUrl);
  }

  return backendResponse;
}

addEventListener("fetch", event => event.respondWith(handler(event)));