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

import { Backend } from "fastly:backend";

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

async function handleRequest(event) {
  const req = event.request;
  const backendNames = ["origin_0", "origin_1"];

  // 1. Shuffle the backends array randomly in-place
  shuffle(backendNames)

  let backend = null;
  // 2. Loop through the randomized backends and find the first healthy one
  for (const backendName of backendNames) {
    let theBackend = Backend.fromName(backendName);

    // Match specifically against the BackendHealth::Healthy enum variant
    if (theBackend.health() == "healthy") {
      console.log(`Found healthy backend: ${backendName}`);
      backend = theBackend;
      break;
    }

    console.log(`Backend ${backendName} is not explicitly healthy, trying next...`);
  }

  // 3. Handle the fallback if absolutely no backends are healthy
  if (backend == null) {
    console.log("All backends are unhealthy or unknown!");
    return new Response("Service Unavailable: No healthy backends available.", {
      status: 503,
    });
  }

  // 4. Send the request to the selected healthy backend
  console.log("Sending request...");
  return await fetch(req, {
    backend,
  });
}

function shuffle(array) {
  let i = array.length, j, temp;
  while (--i > 0) {
    j = Math.floor(Math.random () * (i+1));
    temp = array[j];
    array[j] = array[i];
    array[i] = temp;
  }
}