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

async function handleRequest(event) {
  // Get the request from the client.
  const req = event.request;
  const url = new URL(req.url);
  const params = url.searchParams;

  // Set logger
  const logger = fastly.getLogger("logtest");

  // Set client IP
  let fastlyClientIP = event.client.address;
  logger.log("Client IP is " + fastlyClientIP);

  const banTable = new ConfigStore("ban_dict");

  // Lookup table and get the expiration time for the IP
  if (banTable.get(fastlyClientIP)) {
    const banTime = banTable.get(fastlyClientIP);
    // Conver curernt time to sec
    const currentTime = Math.floor(Date.now() / 1000);

    // Compare ban time and current time
    if (banTime > currentTime) {
      logger.log("Ban in effect for " + fastlyClientIP);
      return new Response(
        "The IP address " + fastlyClientIP + " is banned until " + banTime,
        { status: 403 }
      );
    }
    logger.log(
      "Ban for " +
        fastlyClientIP +
        " expired at " +
        banTime +
        ", allowing access"
    );
  }

  logger.log(fastlyClientIP + " is not banned.");

  // Send the request to `origin_0`.
  const backendResponse = fetch(req, {
    backend: "origin_0"
  });

  // Send the backend response back to the client.
  return backendResponse;
}