use fastly::{Error, Request, Response, ConfigStore, http::StatusCode};
use std::net::IpAddr;
use chrono::{Utc, TimeZone, LocalResult};

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
  let dict = ConfigStore::open("ban_dict");
  let ipaddr: String = match req.get_client_ip_addr().unwrap() {
    IpAddr::V4(x) => x.to_string(),
    IpAddr::V6(x) => x.to_string(),
  };
  println!("Client IP is {}", ipaddr);
  let expire_time = match dict.get(&ipaddr) {
    Some(x) => {
      println!("Expire time is {}", x);
      x.parse::<i64>().unwrap()
    },
    None => {
      println!("{} is not banned.", ipaddr);
      0
    }
  };

  let now = Utc::now();
  let expire_unixtime = match Utc.timestamp_opt(expire_time, 0) {
    LocalResult::Single(x) => x,
    _ => return Ok(Response::from_status(StatusCode::FORBIDDEN).with_body_text_plain(&format!(
      "Ban for {} because {} is not UNIX Time",
      ipaddr,
      expire_time
    ))),
  };
  if (now - expire_unixtime).num_seconds() < 0 {
    return Ok(Response::from_status(StatusCode::FORBIDDEN).with_body_text_plain(&format!(
      "Ban for {} until {} UTC",
      ipaddr,
      expire_unixtime
    )));
  }
  println!("Sending to backend...");
  let beresp = req.send("origin_0")?;

  Ok(beresp)

  // This is a minimal Compute@Edge app in Rust.  For alternative starter
  // code for your fiddle, see the code examples on our developer hub:
  // https://developer.fastly.com/solutions/examples/rust/
}