use fastly::backend::Backend;
use fastly::secret_store::{LookupError, SecretStore};
use fastly::{Error, Request, Response};

#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
    // Fetch the certificate from a secret store
    let store = SecretStore::open("my_credentials_store")?;

    // This is not actually a secret, but it's convenient to store it in
    // the secret store, paired with the key.
    let certificate_bytes = store
        .get("fastly-certificate")
        .ok_or_else(|| LookupError::InvalidSecretName("fastly_certificate".to_string()))?
        .plaintext()
        .to_vec();
    let certificate = String::from_utf8(certificate_bytes)?;

    // This is definitely a secret.
    let certificate_key = store
        .get("fastly-key")
        .ok_or_else(|| LookupError::InvalidSecretName("fastly_key".to_string()))?;

    // mTLS is currently only supported on dynamic backends
    let backend = Backend::builder("origin_0", "http-me.glitch.me")
        .enable_ssl()
        .override_host("http-me.glitch.me")
        .provide_client_certificate(certificate, certificate_key)
        .finish()?;

    Ok(req.send(backend)?)
}