use fastly::{Error, Request, Response};
use fastly::http::StatusCode;
use regex::Regex;

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
  let user_agent = req.get_header_str("user-agent").map(|s| s.to_lowercase());
  
  match user_agent {
      Some(ua) => {
          let ua_pattern = Regex::new(r"badbot|spambot").expect("Invalid regex pattern");

          if ua_pattern.is_match(&ua) {
              Ok(Response::new()
                  .with_status(StatusCode::FORBIDDEN)
                  .with_body("User Agent blocked"))
          } else {
              let beresp = req.send("origin_0")?;
              Ok(beresp)
          }
      }
      None => {
          Ok(Response::new()
              .with_status(StatusCode::FORBIDDEN)
              .with_body("User agent not found"))
      }
  }
}