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

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    let host_header = req.get_header_str(header::HOST).unwrap_or_default();

    if !host_header.starts_with("www.") {
        let mut new_location = req.get_url().clone();
        new_location.set_host(Some(&format!("www.{}", host_header)))?;

        let resp = Response::from_status(StatusCode::PERMANENT_REDIRECT)
            .with_header(header::CACHE_CONTROL, "max-age=86400")
            .with_header(header::LOCATION, new_location);

        return Ok(resp);
    }

    Ok(
        Response::from_body("The page you requested could not be found")
            .with_status(StatusCode::NOT_FOUND),
    )
}