use fastly::{Error, Request, Response};

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    log_fastly::init_simple("mylogs", log::LevelFilter::Info);
    let url_path = req.get_path().to_string();
    // Send the request to the origin    
    let mut beresp = req.send("origin_0")?;

    // Load up the current Surrogate-Key value (if there is one)
    let mut keys = beresp.get_header_str("Surrogate-Key").unwrap_or_default().to_string();

    // Check if the origin is sending back "immutable" in the Cache-Control header
    if beresp.get_header_str("cache-control")
        .map(|cache_control| !cache_control.to_lowercase().contains("immutable"))
        .unwrap_or(true) {
        // Immutable not found, so add the "all" surrogate key
        keys += " all";
    }
    
    // Add the pathname as a surrogate key as well
    keys += &format!(" {}", url_path);

    // Update the Surrogate-Key header with the new keys
    beresp.set_header("Surrogate-Key", keys.trim());

    // Log the surrogate key
    log::info!("Surrogate Keys: {}", keys);

    // Send response to client
    Ok(beresp)
}