use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc, NaiveDate};
use rust_decimal::Decimal;
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::{MaintenanceRequestService, ServiceError};
use crate::presentation::dto::{CreateMaintenanceRequestDto, UpdateMaintenanceRequestDto, PatchMaintenanceRequestDto, MaintenanceRequestResponseDto};
#[derive(Debug, thiserror::Error)]
pub enum MaintenanceRequestError {
#[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("A request cannot be scheduled to finish before it starts.: {0}")]
RequestScheduleEndBeforeStart(String),
#[error("A recurrence step must be at least one unit.: {0}")]
RequestRepeatIntervalBelowOne(String),
#[error("A recurrence bounded 'until' must state its repeat_until date.: {0}")]
RequestRepeatUntilMissing(String),
#[error("Only preventive maintenance may recur.: {0}")]
RequestCorrectiveCannotRecur(String),
#[error("Stage transitions are trigger-consistent; closing a recurring preventive request requires the managed transition verb.: {0}")]
MaintenanceRecurringCloseRequiresServiceVerb(String),
#[error("A stage referenced by live requests cannot be deleted.: {0}")]
MaintenanceStageInUse(String),
#[error("The stage foreign key is real, ON DELETE RESTRICT.: {0}")]
RequestStageFk(String),
}
impl From<ServiceError> for MaintenanceRequestError {
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 MaintenanceRequestError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "MAINTENANCEREQUEST_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "MAINTENANCEREQUEST_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAINTENANCEREQUEST_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAINTENANCEREQUEST_INTERNAL_ERROR"),
Self::RequestScheduleEndBeforeStart(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_REQUEST_SCHEDULE_END_BEFORE_START"),
Self::RequestRepeatIntervalBelowOne(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_REQUEST_REPEAT_INTERVAL_BELOW_ONE"),
Self::RequestRepeatUntilMissing(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_REQUEST_REPEAT_UNTIL_MISSING"),
Self::RequestCorrectiveCannotRecur(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_REQUEST_CORRECTIVE_CANNOT_RECUR"),
Self::MaintenanceRecurringCloseRequiresServiceVerb(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_MAINTENANCE_RECURRING_CLOSE_REQUIRES_SERVICE_VERB"),
Self::MaintenanceStageInUse(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_MAINTENANCE_STAGE_IN_USE"),
Self::RequestStageFk(_) => (StatusCode::UNPROCESSABLE_ENTITY, "MAINTENANCEREQUEST_REQUEST_STAGE_FK"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod maintenance_request_errors {
pub const REQUEST_SCHEDULE_END_BEFORE_START: &str = "MAINTENANCEREQUEST_REQUEST_SCHEDULE_END_BEFORE_START";
pub const REQUEST_REPEAT_INTERVAL_BELOW_ONE: &str = "MAINTENANCEREQUEST_REQUEST_REPEAT_INTERVAL_BELOW_ONE";
pub const REQUEST_REPEAT_UNTIL_MISSING: &str = "MAINTENANCEREQUEST_REQUEST_REPEAT_UNTIL_MISSING";
pub const REQUEST_CORRECTIVE_CANNOT_RECUR: &str = "MAINTENANCEREQUEST_REQUEST_CORRECTIVE_CANNOT_RECUR";
pub const MAINTENANCE_RECURRING_CLOSE_REQUIRES_SERVICE_VERB: &str = "MAINTENANCEREQUEST_MAINTENANCE_RECURRING_CLOSE_REQUIRES_SERVICE_VERB";
pub const MAINTENANCE_STAGE_IN_USE: &str = "MAINTENANCEREQUEST_MAINTENANCE_STAGE_IN_USE";
pub const REQUEST_STAGE_FK: &str = "MAINTENANCEREQUEST_REQUEST_STAGE_FK";
}
pub fn create_maintenance_request_routes(service: Arc<MaintenanceRequestService>) -> Router {
BackboneCrudHandler::<MaintenanceRequestService, MaintenanceRequest, CreateMaintenanceRequestDto, UpdateMaintenanceRequestDto, MaintenanceRequestResponseDto>::routes(
service,
"/maintenance_requests",
)
}
pub fn create_maintenance_request_read_routes(service: Arc<MaintenanceRequestService>) -> Router {
BackboneCrudHandler::<MaintenanceRequestService, MaintenanceRequest, CreateMaintenanceRequestDto, UpdateMaintenanceRequestDto, MaintenanceRequestResponseDto>::read_routes(
service,
"/maintenance_requests",
)
}
pub fn create_maintenance_request_write_routes(service: Arc<MaintenanceRequestService>) -> Router {
BackboneCrudHandler::<MaintenanceRequestService, MaintenanceRequest, CreateMaintenanceRequestDto, UpdateMaintenanceRequestDto, MaintenanceRequestResponseDto>::write_routes(
service,
"/maintenance_requests",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_maintenance_request_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<MaintenanceRequestService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_maintenance_request_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()
}
}
}
}))
}