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

const SYNTH_ERRORS: [StatusCode; 1] = [StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS];
const ERROR_STATUSES: [StatusCode; 2] = [
    StatusCode::INTERNAL_SERVER_ERROR,
    StatusCode::SERVICE_UNAVAILABLE,
];

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    let mut error_req = req.clone_without_body();
    let resp = req.send("origin_0")?;
    match resp.get_status() {
        status if SYNTH_ERRORS.contains(&status) => {
            // Convert status code from origin into a synthetic response.
            Ok(Response::from_status(status).with_body_text_html(&format!(
            r#"<!DOCTYPE html>
        <html lang="en">
        <head>
          <title>There was a problem</title>
          <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet" type="text/css">
          <style>
            body {{ display: inline-block; background: #7000f9 no-repeat; height: 100vh; margin: 0; color: white; }}
            h1 {{ margin: .8em 3rem; font: 4em Roboto; }}
            p {{ display: inline-block; margin: .2em 3rem; font: 2em Roboto; }}
          </style>
        </head>
        <body>
          <h1>{} APOLOGIES!</h1>
          <p>Something went wrong</p>
        </body>
        </html>
"#,
            status)))
        }
        status if ERROR_STATUSES.contains(&status) => {
            // Send a second request for a static error page.
            error_req.set_path("/fastly-fiddle-examples/error-pages/error.html");
            error_req.remove_query();
            Ok(error_req.send("origin_1")?.with_status(status))
        }
        _ => {
            // Use response directly from origin.
            Ok(resp)
        }
    }
}