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::{MailBlacklistService, ServiceError};
use crate::presentation::dto::{CreateMailBlacklistDto, UpdateMailBlacklistDto, PatchMailBlacklistDto, MailBlacklistResponseDto};
#[derive(Debug, thiserror::Error)]
pub enum MailBlacklistError {
#[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("Duplicate blacklisted address — enforced by @unique on MailBlacklist.email. The address is stored LOWERCASED; the write service folds case before insert.: {0}")]
MailBlacklistDuplicateEmail(String),
}
impl From<ServiceError> for MailBlacklistError {
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 MailBlacklistError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "MAILBLACKLIST_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "MAILBLACKLIST_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILBLACKLIST_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILBLACKLIST_INTERNAL_ERROR"),
Self::MailBlacklistDuplicateEmail(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAILBLACKLIST_MAIL_BLACKLIST_DUPLICATE_EMAIL"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod mail_blacklist_errors {
pub const MAIL_BLACKLIST_DUPLICATE_EMAIL: &str = "MAILBLACKLIST_MAIL_BLACKLIST_DUPLICATE_EMAIL";
}
pub fn create_mail_blacklist_routes(service: Arc<MailBlacklistService>) -> Router {
BackboneCrudHandler::<MailBlacklistService, MailBlacklist, CreateMailBlacklistDto, UpdateMailBlacklistDto, MailBlacklistResponseDto>::routes(
service,
"/mail_blacklists",
)
}
pub fn create_mail_blacklist_read_routes(service: Arc<MailBlacklistService>) -> Router {
BackboneCrudHandler::<MailBlacklistService, MailBlacklist, CreateMailBlacklistDto, UpdateMailBlacklistDto, MailBlacklistResponseDto>::read_routes(
service,
"/mail_blacklists",
)
}
pub fn create_mail_blacklist_write_routes(service: Arc<MailBlacklistService>) -> Router {
BackboneCrudHandler::<MailBlacklistService, MailBlacklist, CreateMailBlacklistDto, UpdateMailBlacklistDto, MailBlacklistResponseDto>::write_routes(
service,
"/mail_blacklists",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_mail_blacklist_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<MailBlacklistService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_mail_blacklist_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()
}
}
}
}))
}