backbone-mail 0.2.32

Odoo mail core port — message/notification/followers/activity/alias/sms queue (schema: messaging)
//! MailGuest 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;
use chrono::{DateTime, Utc};

// 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::{MailGuestService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateMailGuestDto, UpdateMailGuestDto, PatchMailGuestDto, MailGuestResponseDto};


/// Application error type
#[derive(Debug, thiserror::Error)]
pub enum MailGuestError {
    #[error("Not found: {0}")]
    NotFound(String),
    #[error("Validation error: {0}")]
    Validation(String),
    #[error("Database error: {0}")]
    Database(String),
    #[error("Internal error: {0}")]
    Internal(String),
}

impl From<ServiceError> for MailGuestError {
    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 MailGuestError {
    fn into_response(self) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::Json;

        let (status, code) = match &self {
            Self::NotFound(_) => (StatusCode::NOT_FOUND, "MAILGUEST_NOT_FOUND"),
            Self::Validation(_) => (StatusCode::BAD_REQUEST, "MAILGUEST_VALIDATION_ERROR"),
            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILGUEST_DATABASE_ERROR"),
            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILGUEST_INTERNAL_ERROR"),
        };

        let body = serde_json::json!({
            "success": false,
            "error": code,
            "message": self.to_string(),
        });

        (status, Json(body)).into_response()
    }
}

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

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

/// Create Axum router with only the read (GET) endpoints for MailGuest.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_mail_guest_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_mail_guest_read_routes(service: Arc<MailGuestService>) -> Router {
    BackboneCrudHandler::<MailGuestService, MailGuest, CreateMailGuestDto, UpdateMailGuestDto, MailGuestResponseDto>::read_routes(
        service,
        "/mail_guests",
    )
}

/// Create Axum router with only the write (mutation) endpoints for MailGuest.
///
/// 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_mail_guest_write_routes(service: Arc<MailGuestService>) -> Router {
    BackboneCrudHandler::<MailGuestService, MailGuest, CreateMailGuestDto, UpdateMailGuestDto, MailGuestResponseDto>::write_routes(
        service,
        "/mail_guests",
    )
}

/// 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_mail_guest_routes<A: AuthMiddleware + Send + Sync + 'static>(
    service: Arc<MailGuestService>,
    auth: Arc<A>,
) -> Router {
    use axum::middleware;
    use axum::response::IntoResponse;

    let auth_layer = auth.clone();
    create_mail_guest_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()
                    }
                }
            }
        }))
}