use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{NaiveDate};
use backbone_core::http::{ApiResponse, BackboneCrudHandler};
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;
use crate::domain::entity::*;
use crate::application::service::{DigestDigestService, ServiceError};
use crate::presentation::dto::{CreateDigestDigestDto, UpdateDigestDigestDto, PatchDigestDigestDto, DigestDigestResponseDto};
use crate::domain::state_machine::{digest_stateState, digest_stateStateMachine, digest_stateTransition};
#[derive(Debug, thiserror::Error)]
pub enum DigestDigestError {
#[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 DigestDigestError {
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()),
ServiceError::Violations(_) => Self::Validation(err.to_string()),
}
}
}
impl axum::response::IntoResponse for DigestDigestError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "DIGESTDIGEST_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "DIGESTDIGEST_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "DIGESTDIGEST_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "DIGESTDIGEST_INTERNAL_ERROR"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub fn create_digest_digest_routes(service: Arc<DigestDigestService>) -> Router {
BackboneCrudHandler::<DigestDigestService, DigestDigest, CreateDigestDigestDto, UpdateDigestDigestDto, DigestDigestResponseDto>::routes(
service,
"/digest_digests",
)
}
pub fn create_digest_digest_read_routes(service: Arc<DigestDigestService>) -> Router {
BackboneCrudHandler::<DigestDigestService, DigestDigest, CreateDigestDigestDto, UpdateDigestDigestDto, DigestDigestResponseDto>::read_routes(
service,
"/digest_digests",
)
}
pub fn create_digest_digest_write_routes(service: Arc<DigestDigestService>) -> Router {
BackboneCrudHandler::<DigestDigestService, DigestDigest, CreateDigestDigestDto, UpdateDigestDigestDto, DigestDigestResponseDto>::write_routes(
service,
"/digest_digests",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_digest_digest_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<DigestDigestService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_digest_digest_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()
}
}
}
}))
}
pub async fn action_activate_transition(
axum::extract::State(service): axum::extract::State<Arc<DigestDigestService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<DigestDigestResponseDto>::not_found("DigestDigest", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<DigestDigestResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = digest_stateTransition::ActionActivate.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "digest_digest:transition:action_activate");
let has_update_perm = auth.permissions.iter().any(|p| p == "digest_digest:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<DigestDigestResponseDto>::error("Insufficient permissions for action_activate transition")));
}
}
let current_state: digest_stateState = entity.state.to_string().parse()
.unwrap_or(digest_stateState::default());
let sm = digest_stateStateMachine::from_state(current_state);
if !sm.can_transition(digest_stateTransition::ActionActivate) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<DigestDigestResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("state".to_string(), serde_json::Value::String("Activated".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: DigestDigestResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<DigestDigestResponseDto>::not_found("DigestDigest", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<DigestDigestResponseDto>::error(e.to_string()))),
}
}
pub async fn action_deactivate_transition(
axum::extract::State(service): axum::extract::State<Arc<DigestDigestService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<DigestDigestResponseDto>::not_found("DigestDigest", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<DigestDigestResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = digest_stateTransition::ActionDeactivate.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "digest_digest:transition:action_deactivate");
let has_update_perm = auth.permissions.iter().any(|p| p == "digest_digest:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<DigestDigestResponseDto>::error("Insufficient permissions for action_deactivate transition")));
}
}
let current_state: digest_stateState = entity.state.to_string().parse()
.unwrap_or(digest_stateState::default());
let sm = digest_stateStateMachine::from_state(current_state);
if !sm.can_transition(digest_stateTransition::ActionDeactivate) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<DigestDigestResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("state".to_string(), serde_json::Value::String("Deactivated".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: DigestDigestResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<DigestDigestResponseDto>::not_found("DigestDigest", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<DigestDigestResponseDto>::error(e.to_string()))),
}
}
pub fn create_digest_digest_transition_routes(service: Arc<DigestDigestService>) -> Router {
use axum::routing::post;
Router::new()
.route("/digest_digests/:id/transitions/action_activate", post(action_activate_transition))
.route("/digest_digests/:id/transitions/action_deactivate", post(action_deactivate_transition))
.with_state(service)
}