backbone-mail 0.2.32

Odoo mail core port — message/notification/followers/activity/alias/sms queue (schema: messaging)
//! SmsTracker REST handlers
//!
//! Generated by metaphor-schema. Do not edit manually.
//!
//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.

use std::collections::HashMap;
use std::sync::Arc;

use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

// Backbone framework imports
use backbone_core::http::BackboneCrudHandler;

// Auth integration (optional)
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;

// Domain imports
use crate::domain::entity::*;
use crate::application::service::{SmsTrackerService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateSmsTrackerDto, UpdateSmsTrackerDto, PatchSmsTrackerDto, SmsTrackerResponseDto};


/// Application error type
#[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),
    // Domain-specific errors from hook rules
    #[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()
    }
}

/// Domain-specific error codes for SmsTracker
pub mod sms_tracker_errors {
    pub const SMS_TRACKER_UUID_DUPLICATE: &str = "SMSTRACKER_SMS_TRACKER_UUID_DUPLICATE";
}

// =============================================================================
// Route Configuration
// =============================================================================

/// Create Axum router with all 16 Backbone endpoints for SmsTracker.
///
/// # Routes
///
/// | Method | Path | Description |
/// |--------|------|-------------|
/// | GET | /sms_trackers | List with pagination |
/// | POST | /sms_trackers | Create new |
/// | GET | /sms_trackers/:id | Get by ID |
/// | PUT | /sms_trackers/:id | Full update |
/// | PATCH | /sms_trackers/:id | Partial update |
/// | DELETE | /sms_trackers/:id | Soft delete |
/// | POST | /sms_trackers/bulk | Bulk create |
/// | POST | /sms_trackers/upsert | Upsert |
/// | GET | /sms_trackers/trash | List deleted |
/// | POST | /sms_trackers/:id/restore | Restore |
/// | DELETE | /sms_trackers/empty | Empty trash |
/// | GET | /sms_trackers/:id/deleted | Get deleted by ID |
/// | DELETE | /sms_trackers/trash/:id | Permanent delete from trash |
/// | GET | /sms_trackers/count | Count active entities |
/// | GET | /sms_trackers/trash/count | Count deleted entities |
///
/// # Example
///
/// ```text
/// let service = Arc::new(SmsTrackerService::with_repository(repository));
/// let router = create_sms_tracker_routes(service);
/// ```
pub fn create_sms_tracker_routes(service: Arc<SmsTrackerService>) -> Router {
    BackboneCrudHandler::<SmsTrackerService, SmsTracker, CreateSmsTrackerDto, UpdateSmsTrackerDto, SmsTrackerResponseDto>::routes(
        service,
        "/sms_trackers",
    )
}

/// Create Axum router with only the read (GET) endpoints for SmsTracker.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_sms_tracker_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_sms_tracker_read_routes(service: Arc<SmsTrackerService>) -> Router {
    BackboneCrudHandler::<SmsTrackerService, SmsTracker, CreateSmsTrackerDto, UpdateSmsTrackerDto, SmsTrackerResponseDto>::read_routes(
        service,
        "/sms_trackers",
    )
}

/// Create Axum router with only the write (mutation) endpoints for SmsTracker.
///
/// These routes must NOT be publicly exposed. Wrap them with an auth
/// middleware before nesting into the application router.
///
/// # This is unguarded generic CRUD, not a validated write path
///
/// These are plain create/update/patch/delete mutations over the entity row —
/// they bypass all business invariants. If the module exposes a validated write
/// service (e.g. a command router over its domain engine), serve THAT instead
/// for any mutation that must respect domain rules.
pub fn create_sms_tracker_write_routes(service: Arc<SmsTrackerService>) -> Router {
    BackboneCrudHandler::<SmsTrackerService, SmsTracker, CreateSmsTrackerDto, UpdateSmsTrackerDto, SmsTrackerResponseDto>::write_routes(
        service,
        "/sms_trackers",
    )
}

/// Create authenticated routes with auth middleware.
///
/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
/// is responsible for extracting and validating tokens, then providing
/// an `AuthContext` via request extensions.
#[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()
                    }
                }
            }
        }))
}