//  Follow instructions at https://docs.fastly.com/guides/streaming-logs/log-streaming-google-bigquery
//  to set up your BigQuery table and add a BigQuery logger to your
//  Fastly service.  This example assumes you have set up a logger
//  called 'myBigQueryLogger' and your BigQuery table has the
//  following schema:
// 
//  timestamp:TIMESTAMP,client_ip:STRING,geo_city:STRING,geo_country_code:STRING,request:STRING,host:STRING,url:STRING,request_referer:STRING,request_user_agent:STRING,request_accept_language:STRING,request_accept_charset:STRING

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

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    let client_geo = req.get_client_ip_addr().and_then(geo_lookup).unwrap();

    // Format log data as JSON object
    let log_data = format!(
        r#"{{"timestamp":"{}","client_ip":"{}","geo_city":"{}","geo_country_code":"{}","request":"{}","host":"{}","url":"{}","request_referer":"{}","request_user_agent":"{}","request_accept_language":"{}","request_accept_charset":"{}"}}"#,
        chrono::Utc::now().to_rfc3339(),
        req.get_client_ip_addr().unwrap_or_else(|| "".parse().unwrap()),
        client_geo.city(),
        client_geo.country_code(),
        req.get_method_str(),
        req.get_url().host_str().unwrap_or_else(||""),
        req.get_url_str(),
        req.get_header_str("referer").unwrap_or_else(||""),
        req.get_header_str("user-agent").unwrap_or_else(||""),
        req.get_header_str("accept-language").unwrap_or_else(||""),
        req.get_header_str("accept-charset").unwrap_or_else(||""));

    //send log data to myBigQueryLogger endpoint
    log_fastly::init_simple("myBigQueryLogger", log::LevelFilter::Info);
    log::info!("{}", &log_data);   
    
    Ok(Response::new())
}