use std::sync::Arc;
use serde::Serialize;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::ephemeral_key::EphemeralKeyResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
#[derive(Debug, Clone)]
pub struct EphemeralKeys {
inner: Arc<Inner>,
}
#[derive(Serialize)]
struct EphemeralKeyCreateBody<'a> {
customer_id: &'a str,
}
impl EphemeralKeys {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(&self, customer_id: &str) -> Result<EphemeralKeyResponse> {
let body = to_json_vec(&EphemeralKeyCreateBody { customer_id })?;
self.inner
.request(HttpMethod::Post, "/ephemeral-keys", Some(&body), &[], None)
.await
}
pub async fn delete(&self, key_id: &str) -> Result<EphemeralKeyResponse> {
let path = format!("/ephemeral-keys/{}", encode_segment(key_id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
}
#[cfg(test)]
mod tests {
use crate::http::mock::{Step, client_with};
const KEY_JSON: &str = r#"{
"customer_id": "cus_1", "created_at": 1700000000,
"expires": 1700003600, "secret": "epk_secret"
}"#;
#[tokio::test]
async fn create_posts_the_customer_id() {
let (client, mock) = client_with(vec![Step::ok(KEY_JSON)]);
let key = client.ephemeral_keys().create("cus_1").await.unwrap();
assert_eq!(key.secret, "epk_secret");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/ephemeral-keys");
assert_eq!(seen[0].body_json()["customer_id"], "cus_1");
}
#[tokio::test]
async fn delete_targets_the_key_path() {
let (client, mock) = client_with(vec![Step::ok(KEY_JSON)]);
client.ephemeral_keys().delete("epk_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/ephemeral-keys/epk_1");
}
}