use std::fmt;
use serde::{Deserialize, Serialize};
use tracing::instrument;
use crate::core::client::UspsClient;
use crate::core::error::{Result, UspsError};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SubscriptionEventType {
TrackingEvents,
PackageDelivered,
DeliveryException,
ReturnToSender,
}
impl fmt::Display for SubscriptionEventType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TrackingEvents => write!(f, "TRACKING_EVENTS"),
Self::PackageDelivered => write!(f, "PACKAGE_DELIVERED"),
Self::DeliveryException => write!(f, "DELIVERY_EXCEPTION"),
Self::ReturnToSender => write!(f, "RETURN_TO_SENDER"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateSubscriptionRequest {
pub callback_url: String,
pub event_types: Vec<SubscriptionEventType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub secret_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
impl CreateSubscriptionRequest {
#[must_use]
pub fn new(callback_url: impl Into<String>, event_types: Vec<SubscriptionEventType>) -> Self {
Self {
callback_url: callback_url.into(),
event_types,
secret_token: None,
description: None,
}
}
#[must_use]
pub fn secret_token(mut self, token: impl Into<String>) -> Self {
self.secret_token = Some(token.into());
self
}
#[must_use]
pub fn description(mut self, desc: impl Into<String>) -> Self {
self.description = Some(desc.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionResponse {
pub subscription_id: String,
pub callback_url: String,
pub status: String,
#[serde(default)]
pub event_types: Vec<String>,
#[serde(default)]
pub created_at: Option<String>,
#[serde(default)]
pub description: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteSubscriptionResponse {
pub status: String,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone)]
pub struct WebhooksService {
client: UspsClient,
}
impl WebhooksService {
#[must_use]
pub(crate) fn new(client: UspsClient) -> Self {
Self { client }
}
#[instrument(skip(self), name = "create_subscription")]
pub async fn subscribe(&self, req: &CreateSubscriptionRequest) -> Result<SubscriptionResponse> {
let url = req.callback_url.trim();
if url.is_empty() || (!url.starts_with("https://") && !url.starts_with("http://")) {
return Err(UspsError::InvalidInput(
"La URL del callback (callback_url) debe ser una URL HTTP/HTTPS válida".to_string(),
));
}
if req.event_types.is_empty() {
return Err(UspsError::InvalidInput(
"Debe seleccionarse al menos un tipo de evento (event_types) para la suscripción"
.to_string(),
));
}
let endpoint = "/subscriptions/v3/subscription";
self.client.post_json(endpoint, req).await
}
#[instrument(skip(self), name = "get_subscription")]
pub async fn get_subscription(&self, subscription_id: &str) -> Result<SubscriptionResponse> {
let clean_id = subscription_id.trim();
if clean_id.is_empty() {
return Err(UspsError::InvalidInput(
"El identificador subscription_id no puede estar vacío".to_string(),
));
}
let endpoint = format!("/subscriptions/v3/subscription/{clean_id}");
let empty_query: [(&str, &str); 0] = [];
self.client.get_with_query(&endpoint, &empty_query).await
}
#[instrument(skip(self), name = "delete_subscription")]
pub async fn delete_subscription(
&self,
subscription_id: &str,
) -> Result<DeleteSubscriptionResponse> {
let clean_id = subscription_id.trim();
if clean_id.is_empty() {
return Err(UspsError::InvalidInput(
"El identificador subscription_id no puede estar vacío".to_string(),
));
}
let endpoint = format!("/subscriptions/v3/subscription/{clean_id}");
let body = self.client.delete(&endpoint).await?;
if body.trim().is_empty() {
Ok(DeleteSubscriptionResponse {
status: "DELETED".to_string(),
message: Some(format!(
"Suscripción {clean_id} eliminada satisfactoriamente"
)),
})
} else {
serde_json::from_str::<DeleteSubscriptionResponse>(&body)
.map_err(UspsError::Serialization)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_subscription_request_builder() {
let req = CreateSubscriptionRequest::new(
"https://api.myapp.com/webhooks/usps",
vec![
SubscriptionEventType::PackageDelivered,
SubscriptionEventType::DeliveryException,
],
)
.secret_token("super_secret_hmac_key")
.description("Producción e-commerce");
assert_eq!(req.callback_url, "https://api.myapp.com/webhooks/usps");
assert_eq!(req.event_types.len(), 2);
assert_eq!(req.secret_token.as_deref(), Some("super_secret_hmac_key"));
assert_eq!(req.description.as_deref(), Some("Producción e-commerce"));
}
#[test]
fn subscription_response_deserialization() {
let json = r#"{
"subscriptionId": "SUB-12345",
"callbackUrl": "https://api.myapp.com/webhooks/usps",
"status": "ACTIVE",
"eventTypes": ["PACKAGE_DELIVERED"],
"createdAt": "2026-09-15T20:00:00Z"
}"#;
let res: SubscriptionResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.subscription_id, "SUB-12345");
assert_eq!(res.callback_url, "https://api.myapp.com/webhooks/usps");
assert_eq!(res.status, "ACTIVE");
assert_eq!(res.event_types, vec!["PACKAGE_DELIVERED"]);
}
}