use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
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::{BoothService, ServiceError};
use crate::presentation::dto::{CreateBoothDto, UpdateBoothDto, PatchBoothDto, BoothResponseDto};
use crate::domain::state_machine::{booth_stateState, booth_stateStateMachine, booth_stateTransition};
#[derive(Debug, thiserror::Error)]
pub enum BoothError {
#[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 BoothError {
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 BoothError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "BOOTH_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "BOOTH_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BOOTH_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BOOTH_INTERNAL_ERROR"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub fn create_booth_routes(service: Arc<BoothService>) -> Router {
BackboneCrudHandler::<BoothService, Booth, CreateBoothDto, UpdateBoothDto, BoothResponseDto>::routes(
service,
"/booths",
)
}
pub fn create_booth_read_routes(service: Arc<BoothService>) -> Router {
BackboneCrudHandler::<BoothService, Booth, CreateBoothDto, UpdateBoothDto, BoothResponseDto>::read_routes(
service,
"/booths",
)
}
pub fn create_booth_write_routes(service: Arc<BoothService>) -> Router {
BackboneCrudHandler::<BoothService, Booth, CreateBoothDto, UpdateBoothDto, BoothResponseDto>::write_routes(
service,
"/booths",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_booth_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<BoothService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_booth_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 confirm_transition(
axum::extract::State(service): axum::extract::State<Arc<BoothService>>,
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::<BoothResponseDto>::not_found("Booth", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BoothResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = booth_stateTransition::Confirm.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "booth:transition:confirm");
let has_update_perm = auth.permissions.iter().any(|p| p == "booth:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<BoothResponseDto>::error("Insufficient permissions for confirm transition")));
}
}
let current_state: booth_stateState = entity.state.to_string().parse()
.unwrap_or(booth_stateState::default());
let sm = booth_stateStateMachine::from_state(current_state);
if !sm.can_transition(booth_stateTransition::Confirm) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BoothResponseDto>::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("Unavailable".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: BoothResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BoothResponseDto>::not_found("Booth", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BoothResponseDto>::error(e.to_string()))),
}
}
pub async fn release_transition(
axum::extract::State(service): axum::extract::State<Arc<BoothService>>,
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::<BoothResponseDto>::not_found("Booth", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BoothResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = booth_stateTransition::Release.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "booth:transition:release");
let has_update_perm = auth.permissions.iter().any(|p| p == "booth:update");
if !has_specific_perm && !has_update_perm {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<BoothResponseDto>::error("Insufficient permissions for release transition")));
}
}
let current_state: booth_stateState = entity.state.to_string().parse()
.unwrap_or(booth_stateState::default());
let sm = booth_stateStateMachine::from_state(current_state);
if !sm.can_transition(booth_stateTransition::Release) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BoothResponseDto>::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("Available".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: BoothResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BoothResponseDto>::not_found("Booth", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BoothResponseDto>::error(e.to_string()))),
}
}
pub fn create_booth_transition_routes(service: Arc<BoothService>) -> Router {
use axum::routing::post;
Router::new()
.route("/booths/:id/transitions/confirm", post(confirm_transition))
.route("/booths/:id/transitions/release", post(release_transition))
.with_state(service)
}