use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};
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::{UserQuotaService, ServiceError};
use crate::presentation::dto::{CreateUserQuotaDto, UpdateUserQuotaDto, PatchUserQuotaDto, UserQuotaResponseDto};
use crate::domain::state_machine::{UserQuotaState, UserQuotaStateMachine, UserQuotaTransition};
#[derive(Debug, thiserror::Error)]
pub enum UserQuotaError {
#[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("User does not exist: {0}")]
UserNotFound(String),
#[error("User already has a quota record: {0}")]
QuotaExists(String),
#[error("Invalid tier. Must be free, pro, or enterprise: {0}")]
InvalidTier(String),
#[error("Max storage must be positive: {0}")]
InvalidMaxStorage(String),
#[error("Max file size must be positive: {0}")]
InvalidMaxFileSize(String),
#[error("Max file size cannot exceed max storage: {0}")]
FileSizeExceedsStorage(String),
#[error("Cannot downgrade tier: current usage exceeds new quota limits: {0}")]
DowngradeNotAllowed(String),
#[error("Warning threshold must be between 50 and 99 percent: {0}")]
InvalidWarningThreshold(String),
}
impl From<ServiceError> for UserQuotaError {
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 UserQuotaError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "USERQUOTA_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "USERQUOTA_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "USERQUOTA_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "USERQUOTA_INTERNAL_ERROR"),
Self::UserNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_USER_NOT_FOUND"),
Self::QuotaExists(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_QUOTA_EXISTS"),
Self::InvalidTier(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_TIER"),
Self::InvalidMaxStorage(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_MAX_STORAGE"),
Self::InvalidMaxFileSize(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_MAX_FILE_SIZE"),
Self::FileSizeExceedsStorage(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_FILE_SIZE_EXCEEDS_STORAGE"),
Self::DowngradeNotAllowed(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_DOWNGRADE_NOT_ALLOWED"),
Self::InvalidWarningThreshold(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_WARNING_THRESHOLD"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod user_quota_errors {
pub const USER_NOT_FOUND: &str = "USERQUOTA_USER_NOT_FOUND";
pub const QUOTA_EXISTS: &str = "USERQUOTA_QUOTA_EXISTS";
pub const INVALID_TIER: &str = "USERQUOTA_INVALID_TIER";
pub const INVALID_MAX_STORAGE: &str = "USERQUOTA_INVALID_MAX_STORAGE";
pub const INVALID_MAX_FILE_SIZE: &str = "USERQUOTA_INVALID_MAX_FILE_SIZE";
pub const FILE_SIZE_EXCEEDS_STORAGE: &str = "USERQUOTA_FILE_SIZE_EXCEEDS_STORAGE";
pub const DOWNGRADE_NOT_ALLOWED: &str = "USERQUOTA_DOWNGRADE_NOT_ALLOWED";
pub const INVALID_WARNING_THRESHOLD: &str = "USERQUOTA_INVALID_WARNING_THRESHOLD";
}
pub fn create_user_quota_routes(service: Arc<UserQuotaService>) -> Router {
BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::routes(
service,
"/user_quotas",
)
}
pub fn create_user_quota_read_routes(service: Arc<UserQuotaService>) -> Router {
BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::read_routes(
service,
"/user_quotas",
)
}
pub fn create_user_quota_write_routes(service: Arc<UserQuotaService>) -> Router {
BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::write_routes(
service,
"/user_quotas",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_user_quota_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<UserQuotaService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_user_quota_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 exceed_transition(
axum::extract::State(service): axum::extract::State<Arc<UserQuotaService>>,
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::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = UserQuotaTransition::Exceed.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "user_quota:transition:exceed");
let has_update_perm = auth.permissions.iter().any(|p| p == "user_quota:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<UserQuotaResponseDto>::error("Insufficient permissions for exceed transition")));
}
}
let current_state: UserQuotaState = entity.quota_status.to_string().parse()
.unwrap_or(UserQuotaState::default());
let sm = UserQuotaStateMachine::from_state(current_state);
if !sm.can_transition(UserQuotaTransition::Exceed) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<UserQuotaResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("quota_status".to_string(), serde_json::Value::String("Exceeded".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: UserQuotaResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
}
}
pub async fn restore_transition(
axum::extract::State(service): axum::extract::State<Arc<UserQuotaService>>,
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::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = UserQuotaTransition::Restore.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "user_quota:transition:restore");
let has_update_perm = auth.permissions.iter().any(|p| p == "user_quota:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<UserQuotaResponseDto>::error("Insufficient permissions for restore transition")));
}
}
let current_state: UserQuotaState = entity.quota_status.to_string().parse()
.unwrap_or(UserQuotaState::default());
let sm = UserQuotaStateMachine::from_state(current_state);
if !sm.can_transition(UserQuotaTransition::Restore) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<UserQuotaResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("quota_status".to_string(), serde_json::Value::String("Normal".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: UserQuotaResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
}
}
pub fn create_user_quota_transition_routes(service: Arc<UserQuotaService>) -> Router {
use axum::routing::post;
Router::new()
.route("/user_quotas/:id/transitions/exceed", post(exceed_transition))
.route("/user_quotas/:id/transitions/restore", post(restore_transition))
.with_state(service)
}