use fastly::{Error, Request, Response, http::HeaderValue};
use rand::Rng;
use chrono::Utc;

#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
   let mut resp = req.clone_with_body().send("origin_0")?;

   if !req.get_header("Cookie").unwrap_or(&HeaderValue::from_static("")).to_str().unwrap().contains("_ga")
    {
        println!("{}", req.get_header("Host").unwrap().to_str().unwrap());
        let domainsegscount = req.get_header("Host").unwrap_or(&HeaderValue::from_static("")).to_str().unwrap().chars().filter(|&c| c=='.').count()+1;
        let cookie_value = format!(
            "_ga=GA1.{}.{}.{:.0}; Domain=.fiddle.fastlydemo.net; Max-Age=63072000",
            domainsegscount,
            rand::thread_rng().gen_range(1000000000..2147483647),
            Utc::now().timestamp()
        );

        //add set-cookie header
        resp.set_header("Set-Cookie", &HeaderValue::from_str(&cookie_value).unwrap());
        
        //  Prevent browser from caching a set-cookie
        resp.set_header("Cache-Control", &HeaderValue::from_static("no-store"));
    }
    
    Ok(resp)
}