use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use backbone_core::http::BackboneCrudHandler;
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;
use crate::domain::entity::*;
use crate::application::service::{SmsTrackerService, ServiceError};
use crate::presentation::dto::{CreateSmsTrackerDto, UpdateSmsTrackerDto, PatchSmsTrackerDto, SmsTrackerResponseDto};
#[derive(Debug, thiserror::Error)]
pub enum SmsTrackerError {
#[error("Not found: {0}")]
NotFound(String),
#[error("Validation error: {0}")]
Validation(String),
#[error("Database error: {0}")]
Database(String),
#[error("Internal error: {0}")]
Internal(String),
#[error("sms.tracker _sms_uuid_unique — the 1:1 uuid↔tracker guarantee. Because the tracker is decoupled from sms.id by design (sent rows are GC'd), this unique is what enforces the correspondence. Enforced by @unique on SmsTracker.sms_uuid (fires on raw SQL).: {0}")]
SmsTrackerUuidDuplicate(String),
}
impl From<ServiceError> for SmsTrackerError {
fn from(err: ServiceError) -> Self {
match err {
ServiceError::NotFound => Self::NotFound(err.to_string()),
ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
ServiceError::Repository(ref e) => Self::Database(e.to_string()),
ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
}
}
}
impl axum::response::IntoResponse for SmsTrackerError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "SMSTRACKER_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "SMSTRACKER_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SMSTRACKER_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "SMSTRACKER_INTERNAL_ERROR"),
Self::SmsTrackerUuidDuplicate(_) => (StatusCode::UNPROCESSABLE_ENTITY, "SMSTRACKER_SMS_TRACKER_UUID_DUPLICATE"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod sms_tracker_errors {
pub const SMS_TRACKER_UUID_DUPLICATE: &str = "SMSTRACKER_SMS_TRACKER_UUID_DUPLICATE";
}
pub fn create_sms_tracker_routes(service: Arc<SmsTrackerService>) -> Router {
BackboneCrudHandler::<SmsTrackerService, SmsTracker, CreateSmsTrackerDto, UpdateSmsTrackerDto, SmsTrackerResponseDto>::routes(
service,
"/sms_trackers",
)
}
pub fn create_sms_tracker_read_routes(service: Arc<SmsTrackerService>) -> Router {
BackboneCrudHandler::<SmsTrackerService, SmsTracker, CreateSmsTrackerDto, UpdateSmsTrackerDto, SmsTrackerResponseDto>::read_routes(
service,
"/sms_trackers",
)
}
pub fn create_sms_tracker_write_routes(service: Arc<SmsTrackerService>) -> Router {
BackboneCrudHandler::<SmsTrackerService, SmsTracker, CreateSmsTrackerDto, UpdateSmsTrackerDto, SmsTrackerResponseDto>::write_routes(
service,
"/sms_trackers",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_sms_tracker_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<SmsTrackerService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_sms_tracker_routes(service)
.layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
let auth = auth_layer.clone();
async move {
let token = req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|h| h.to_str().ok())
.and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
.unwrap_or("");
match auth.authenticate(token).await {
Ok(ctx) => {
req.extensions_mut().insert(ctx);
next.run(req).await
}
Err(_) => {
(axum::http::StatusCode::UNAUTHORIZED,
axum::Json(serde_json::json!({
"success": false,
"error": "unauthorized",
"message": "Authentication required"
}))
).into_response()
}
}
}
}))
}