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

/// The name of a backend server associated with this service.
const BACKEND_NAME = "origin_0";

/// The name of google cloud storage bucket name
const BUCKET_NAME = "betts-gcp-gcs-fastly-tutorial";

async function handleRequest(event) {
  // Get the client request from the event
  const originalReq = event.request;

  // Fetch the index page if the request is for a directory
  let url = new URL(originalReq.url);
  let page = "";
  if (url.pathname.endsWith("/")) {
    page = "index.html";
  }
  url.pathname = "/" + BUCKET_NAME + url.pathname + page;
  let newReq = new Request(url, originalReq);
  // Set the host header for backend access
  newReq.headers.set("Host", "storage.googleapis.com");

  // Send the request to backend
  let resp = await fetch(newReq, {
    backend: BACKEND_NAME,
  });

  if (resp.status == 404 && !url.pathname.endsWith("/index.html")) {
    // Not found, and not already an index page, try again for the directory index
    url = new URL(originalReq.url);
    let directory_path = url.pathname + "/";
    url.pathname = "/" + BUCKET_NAME + url.pathname + "/index.html";

    // Make a new request from path with directory index page
    newReq = new Request(url, originalReq);
    // Set the host header for backend access
    newReq.headers.set("Host", "storage.googleapis.com");

    // Send the retry request to backend
    resp = await fetch(newReq, {
      backend: BACKEND_NAME,
    });

    if (resp.status == 200) {
      // Retry for a directory index page has succeeded, redirect externally to the directory URL.
      let headers = new Headers({"location": directory_path});
      resp = new Response('', {status: 301, headers});
    }
  }

  return resp;
};