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

#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
  // Browsers identify the intended purpose of a request via the
  // Sec-Fetch-Dest header (https://w3c.github.io/webappsec-fetch-metadata/)
  let mut strip_query = match req.get_header_str("Sec-Fetch-Dest") {
    Some(content_type) => {
      let content_regex = Regex::new(r"^(audio|audioworklet|embed|font|image|manifest|object|paintworklet|script|sharedworker|style|track|video|worker|xslt)$")?;
      content_regex.is_match(content_type)
    },
    None => false
  };

  // The above header is usually a good indicator but you should also strip querystrings
  // from any other URLs that you know are not affected by querystring.
  let path_regex = Regex::new(r"\.(jpe?g|gif|png|webp|css|)$")?;
  if path_regex.is_match(req.get_url().path()) {
    strip_query = true;
  }

  // If the previous checks determined we should remove the query string...
  if strip_query {
    println!("Removing query string from URL {}", req.get_url());
    // Remove the query string from the request URL.
    req.get_url_mut().set_query(None);
    println!("URL forwarded to origin is {}", req.get_url());
  }

  // Forward the modified client request to the origin.
  let beresp = req.send("origin_0")?;

  // Send the backend response to the client.
  Ok(beresp)
}