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 LocationServiceType {
PassportAppointments,
PoBoxes,
RetailServices,
CollectionBox,
SelfServiceKiosks,
BulkMailAcceptance,
GreetingCardsSupplies,
DuckStamps,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DailyHours {
pub day_of_the_week: String,
#[serde(default)]
pub open_time: Option<String>,
#[serde(default)]
pub close_time: Option<String>,
#[serde(default)]
pub is_closed: bool,
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocationFacility {
pub location_id: String,
pub name: String,
#[serde(default)]
pub location_type: Option<String>,
pub street_address: String,
pub city: String,
pub state: String,
#[serde(rename = "ZIPCode")]
pub zip_code: String,
#[serde(rename = "ZIPPlus4", default)]
pub zip_plus4: Option<String>,
#[serde(default)]
pub phone: Option<String>,
#[serde(default)]
pub latitude: Option<f64>,
#[serde(default)]
pub longitude: Option<f64>,
#[serde(default)]
pub distance: Option<f64>,
#[serde(default)]
pub operating_hours: Vec<DailyHours>,
#[serde(default)]
pub services: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocationSearchRequest {
#[serde(rename = "ZIPCode", skip_serializing_if = "Option::is_none")]
pub zip_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub latitude: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub longitude: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub radius: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_type: Option<LocationServiceType>,
}
impl LocationSearchRequest {
#[must_use]
pub fn from_zip_code(zip_code: impl Into<String>) -> Self {
Self {
zip_code: Some(zip_code.into()),
radius: Some(10),
max_results: Some(20),
..Default::default()
}
}
#[must_use]
pub fn from_coordinates(latitude: f64, longitude: f64) -> Self {
Self {
latitude: Some(latitude),
longitude: Some(longitude),
radius: Some(10),
max_results: Some(20),
..Default::default()
}
}
#[must_use]
pub fn radius(mut self, miles: u32) -> Self {
self.radius = Some(miles);
self
}
#[must_use]
pub fn max_results(mut self, limit: u32) -> Self {
self.max_results = Some(limit);
self
}
#[must_use]
pub fn with_service(mut self, service: LocationServiceType) -> Self {
self.service_type = Some(service);
self
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocationSearchResponse {
#[serde(default)]
pub locations: Vec<LocationFacility>,
#[serde(default)]
pub total_locations: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct LocationsService {
client: UspsClient,
}
impl LocationsService {
#[must_use]
pub(crate) fn new(client: UspsClient) -> Self {
Self { client }
}
#[instrument(skip(self), name = "search_locations")]
pub async fn search(&self, req: &LocationSearchRequest) -> Result<LocationSearchResponse> {
if req.zip_code.is_none() && (req.latitude.is_none() || req.longitude.is_none()) {
return Err(UspsError::InvalidInput(
"Debe proporcionarse un código postal o coordenadas (latitud/longitud) para la búsqueda".to_string(),
));
}
if let Some(ref zip) = req.zip_code {
let trimmed = zip.trim();
if trimmed.len() != 5 || !trimmed.chars().all(|c| c.is_ascii_digit()) {
return Err(UspsError::InvalidInput(
"El código postal debe contener exactamente 5 dígitos numéricos".to_string(),
));
}
}
let endpoint = "/locations/v3/location";
self.client.get_with_query(endpoint, req).await
}
#[instrument(skip(self), name = "get_location_details")]
pub async fn get_details(&self, location_id: &str) -> Result<LocationFacility> {
let clean_id = location_id.trim();
if clean_id.is_empty() {
return Err(UspsError::InvalidInput(
"El identificador location_id no puede estar vacío".to_string(),
));
}
let endpoint = format!("/locations/v3/location/{clean_id}");
let empty_query: [(&str, &str); 0] = [];
self.client.get_with_query(&endpoint, &empty_query).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn location_search_request_from_zip() {
let req = LocationSearchRequest::from_zip_code("20260")
.radius(15)
.max_results(5)
.with_service(LocationServiceType::PassportAppointments);
assert_eq!(req.zip_code.as_deref(), Some("20260"));
assert_eq!(req.radius, Some(15));
assert_eq!(req.max_results, Some(5));
assert_eq!(
req.service_type,
Some(LocationServiceType::PassportAppointments)
);
}
#[test]
fn location_search_response_deserialization() {
let json = r#"{
"locations": [
{
"locationId": "1380568",
"name": "CURLEEN POST OFFICE",
"locationType": "POST_OFFICE",
"streetAddress": "475 LENFANT PLZ SW",
"city": "WASHINGTON",
"state": "DC",
"ZIPCode": "20260",
"phone": "800-275-8777",
"distance": 0.3,
"operatingHours": [
{
"dayOfTheWeek": "Monday",
"openTime": "08:30",
"closeTime": "17:00",
"isClosed": false
}
],
"services": [
"PO_BOXES",
"PASSPORT_APPOINTMENTS"
]
}
],
"totalLocations": 1
}"#;
let res: LocationSearchResponse = serde_json::from_str(json).unwrap();
assert_eq!(res.locations.len(), 1);
let loc = &res.locations[0];
assert_eq!(loc.location_id, "1380568");
assert_eq!(loc.name, "CURLEEN POST OFFICE");
assert_eq!(loc.city, "WASHINGTON");
assert_eq!(loc.distance, Some(0.3));
assert_eq!(loc.operating_hours.len(), 1);
assert_eq!(loc.operating_hours[0].day_of_the_week, "Monday");
assert_eq!(loc.services.len(), 2);
}
}