use fastly::experimental::{BackendExt, BackendHealth};
use fastly::{Backend, Error, Request, Response};
use rand::seq::SliceRandom;

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    let mut backends = ["origin_0", "origin_1"];
    let mut rng = rand::thread_rng();
    
    // 1. Shuffle the backends array randomly in-place
    backends.shuffle(&mut rng);

    let mut chosen_backend = None;

    // 2. Loop through the randomized backends and find the first healthy one
    for name in &backends {
        let backend = Backend::from_name(name)
          .unwrap();
        
        // Match specifically against the BackendHealth::Healthy enum variant
        if let Ok(BackendHealth::Healthy) = backend.is_healthy() {
            println!("Found healthy backend: {}", name);
            chosen_backend = Some(backend);
            break;
        }
        
        println!("Backend {} is not explicitly healthy, trying next...", name);
    }

    // 3. Handle the fallback if absolutely no backends are healthy
    if chosen_backend.is_none() {
        println!("All backends are unhealthy or unknown!");
        return Ok(Response::from_status(503)
            .with_body("Service Unavailable: No healthy backends available."));
    }

    // 4. Send the request to the selected healthy backend
    println!("Sending request...");
    let backend = chosen_backend.unwrap();
    let beresp = req.send(backend)?;

    Ok(beresp)
}