/// <reference types="@fastly/js-compute" />

// The max number of redirects allowed.
const maxRedirectCount = 2;

// The number of redirects followed.
let redirectCount = 0;

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

async function handleRequest(event) {
  const request = event.request;
  const reqHost = request.headers.get('host');

  let beResp = await fetch(request, {
    backend: "origin_0",
  });
  console.log("Backend Response :", beResp);

  while (
    isRedirect(beResp.status) &&
    beResp.headers.has('location') &&
    urlHasHost(beResp.headers.get('location'), reqHost) &&
    redirectCount <= maxRedirectCount
  ) {
    
    redirectCount++;

    // Reset the URL path.
    // NOTE: This solution works for same-origin redirects only.
    const redirectPath = parsePath(beResp.headers.get("Location"), reqHost);
    console.log(`Redirect URL (count: ${redirectCount}): ${redirectPath}`);

    // Send the request to the named backend.
    let newRequest = new Request(redirectPath, { headers: beResp.headers });
    beResp = await fetch(newRequest, {
      backend: "origin_0",
    });
  }
  return beResp;
}

function isRedirect(statusCode) {
  return statusCode >= 300 && statusCode < 400;
}

function urlHasHost(locationStr, host) {
  if (locationStr.startsWith('/')) return true;
  const url = new URL(locationStr);
  return (url.hostname === host);
}

function parsePath(locationStr, host) {
  if (locationStr.startsWith('/')) {
    locationStr = `https://${host}${locationStr}`;
  }
  const url = new URL(locationStr);
  return url.pathname;
}