use std::fmt;
use std::time::Duration;
use super::error::{Result, UspsError};
use super::retry::RetryPolicy;
pub const USPS_CAT_BASE_URL: &str = "https://api-cat.usps.com";
pub const USPS_PROD_BASE_URL: &str = "https://api.usps.com";
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum UspsEnvironment {
#[default]
Sandbox,
Production,
Custom(String),
}
impl UspsEnvironment {
#[must_use]
pub fn base_url(&self) -> &str {
match self {
Self::Sandbox => USPS_CAT_BASE_URL,
Self::Production => USPS_PROD_BASE_URL,
Self::Custom(custom_url) => custom_url.trim_end_matches('/'),
}
}
}
#[derive(Clone)]
pub struct UspsConfig {
pub client_id: String,
pub client_secret: String,
pub environment: UspsEnvironment,
pub timeout: Duration,
pub retry_policy: RetryPolicy,
}
impl fmt::Debug for UspsConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UspsConfig")
.field("client_id", &self.client_id)
.field("client_secret", &"[REDACTED]")
.field("environment", &self.environment)
.field("timeout", &self.timeout)
.field("retry_policy", &self.retry_policy)
.finish()
}
}
impl UspsConfig {
pub fn new(
client_id: impl Into<String>,
client_secret: impl Into<String>,
environment: UspsEnvironment,
) -> Result<Self> {
let client_id = client_id.into().trim().to_string();
let client_secret = client_secret.into().trim().to_string();
if client_id.is_empty() {
return Err(UspsError::InvalidInput(
"El client_id no puede estar vacío".to_string(),
));
}
if client_secret.is_empty() {
return Err(UspsError::InvalidInput(
"El client_secret no puede estar vacío".to_string(),
));
}
Ok(Self {
client_id,
client_secret,
environment,
timeout: Duration::from_secs(30),
retry_policy: RetryPolicy::default(),
})
}
#[must_use]
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
self.retry_policy = policy;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_should_sanitize_debug_logs() {
let config =
UspsConfig::new("my-client-id", "super-secret-key", UspsEnvironment::Sandbox).unwrap();
let debug_str = format!("{config:?}");
assert!(debug_str.contains("my-client-id"));
assert!(!debug_str.contains("super-secret-key"));
assert!(debug_str.contains("[REDACTED]"));
}
#[test]
fn config_should_fail_on_empty_credentials() {
let err = UspsConfig::new("", "secret", UspsEnvironment::Sandbox).unwrap_err();
assert!(matches!(err, UspsError::InvalidInput(_)));
let err = UspsConfig::new("id", "", UspsEnvironment::Sandbox).unwrap_err();
assert!(matches!(err, UspsError::InvalidInput(_)));
}
#[test]
fn environment_should_return_correct_base_url() {
assert_eq!(UspsEnvironment::Sandbox.base_url(), USPS_CAT_BASE_URL);
assert_eq!(UspsEnvironment::Production.base_url(), USPS_PROD_BASE_URL);
assert_eq!(
UspsEnvironment::Custom("https://my-proxy.com/api/".to_string()).base_url(),
"https://my-proxy.com/api"
);
}
}