Skip to main content

backbone_bucket/presentation/http/
bucket_handler.rs

1//! Bucket REST handlers
2//!
3//! Generated by metaphor-schema. Do not edit manually.
4//!
5//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14// Backbone framework imports
15use backbone_core::http::{ApiResponse, BackboneCrudHandler};
16
17// Auth integration (optional)
18#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23// Domain imports
24use crate::domain::entity::*;
25use crate::application::service::{BucketService, ServiceError};
26
27// DTO imports
28use crate::presentation::dto::{CreateBucketDto, UpdateBucketDto, PatchBucketDto, BucketResponseDto};
29
30use crate::domain::state_machine::{BucketState, BucketStateMachine, BucketTransition};
31
32/// Application error type
33#[derive(Debug, thiserror::Error)]
34pub enum BucketError {
35    #[error("Not found: {0}")]
36    NotFound(String),
37    #[error("Validation error: {0}")]
38    Validation(String),
39    #[error("Database error: {0}")]
40    Database(String),
41    #[error("Internal error: {0}")]
42    Internal(String),
43    // Domain-specific errors from hook rules
44    #[error("Bucket name must be 1-255 characters: {0}")]
45    InvalidNameLength(String),
46    #[error("Bucket name must contain only alphanumeric characters, underscores, and hyphens: {0}")]
47    InvalidNameChars(String),
48    #[error("Bucket slug must be 1-255 characters: {0}")]
49    InvalidSlugLength(String),
50    #[error("Bucket slug must be lowercase with hyphens only: {0}")]
51    InvalidSlugChars(String),
52    #[error("Root path too long: {0}")]
53    PathTooLong(String),
54    #[error("Path traversal not allowed in root path: {0}")]
55    PathTraversal(String),
56    #[error("Cannot modify deleted buckets: {0}")]
57    BucketDeleted(String),
58    #[error("Bucket slug is already taken: {0}")]
59    SlugExists(String),
60}
61
62impl From<ServiceError> for BucketError {
63    fn from(err: ServiceError) -> Self {
64        match err {
65            ServiceError::NotFound => Self::NotFound(err.to_string()),
66            ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
67            ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
68            ServiceError::Repository(ref e) => Self::Database(e.to_string()),
69            ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
70            ServiceError::Violations(_) => Self::Validation(err.to_string()),
71        }
72    }
73}
74
75impl axum::response::IntoResponse for BucketError {
76    fn into_response(self) -> axum::response::Response {
77        use axum::http::StatusCode;
78        use axum::Json;
79
80        let (status, code) = match &self {
81            Self::NotFound(_) => (StatusCode::NOT_FOUND, "BUCKET_NOT_FOUND"),
82            Self::Validation(_) => (StatusCode::BAD_REQUEST, "BUCKET_VALIDATION_ERROR"),
83            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BUCKET_DATABASE_ERROR"),
84            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BUCKET_INTERNAL_ERROR"),
85            Self::InvalidNameLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_NAME_LENGTH"),
86            Self::InvalidNameChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_NAME_CHARS"),
87            Self::InvalidSlugLength(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_SLUG_LENGTH"),
88            Self::InvalidSlugChars(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_INVALID_SLUG_CHARS"),
89            Self::PathTooLong(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_PATH_TOO_LONG"),
90            Self::PathTraversal(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_PATH_TRAVERSAL"),
91            Self::BucketDeleted(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_BUCKET_DELETED"),
92            Self::SlugExists(_) => (StatusCode::UNPROCESSABLE_ENTITY, "BUCKET_SLUG_EXISTS"),
93        };
94
95        let body = serde_json::json!({
96            "success": false,
97            "error": code,
98            "message": self.to_string(),
99        });
100
101        (status, Json(body)).into_response()
102    }
103}
104
105/// Domain-specific error codes for Bucket
106pub mod bucket_errors {
107    pub const INVALID_NAME_LENGTH: &str = "BUCKET_INVALID_NAME_LENGTH";
108    pub const INVALID_NAME_CHARS: &str = "BUCKET_INVALID_NAME_CHARS";
109    pub const INVALID_SLUG_LENGTH: &str = "BUCKET_INVALID_SLUG_LENGTH";
110    pub const INVALID_SLUG_CHARS: &str = "BUCKET_INVALID_SLUG_CHARS";
111    pub const PATH_TOO_LONG: &str = "BUCKET_PATH_TOO_LONG";
112    pub const PATH_TRAVERSAL: &str = "BUCKET_PATH_TRAVERSAL";
113    pub const BUCKET_DELETED: &str = "BUCKET_BUCKET_DELETED";
114    pub const SLUG_EXISTS: &str = "BUCKET_SLUG_EXISTS";
115}
116
117// =============================================================================
118// Route Configuration
119// =============================================================================
120
121/// Create Axum router with all 16 Backbone endpoints for Bucket.
122///
123/// # Routes
124///
125/// | Method | Path | Description |
126/// |--------|------|-------------|
127/// | GET | /buckets | List with pagination |
128/// | POST | /buckets | Create new |
129/// | GET | /buckets/:id | Get by ID |
130/// | PUT | /buckets/:id | Full update |
131/// | PATCH | /buckets/:id | Partial update |
132/// | DELETE | /buckets/:id | Soft delete |
133/// | POST | /buckets/bulk | Bulk create |
134/// | POST | /buckets/upsert | Upsert |
135/// | GET | /buckets/trash | List deleted |
136/// | POST | /buckets/:id/restore | Restore |
137/// | DELETE | /buckets/empty | Empty trash |
138/// | GET | /buckets/:id/deleted | Get deleted by ID |
139/// | DELETE | /buckets/trash/:id | Permanent delete from trash |
140/// | GET | /buckets/count | Count active entities |
141/// | GET | /buckets/trash/count | Count deleted entities |
142///
143/// # Example
144///
145/// ```text
146/// let service = Arc::new(BucketService::with_repository(repository));
147/// let router = create_bucket_routes(service);
148/// ```
149pub fn create_bucket_routes(service: Arc<BucketService>) -> Router {
150    BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::routes(
151        service,
152        "/buckets",
153    )
154}
155
156/// Create Axum router with only the read (GET) endpoints for Bucket.
157///
158/// Safe for public, unauthenticated exposure (e.g., reference data).
159/// Mutations must be served separately via `create_bucket_write_routes`,
160/// typically wrapped in an auth middleware layer.
161pub fn create_bucket_read_routes(service: Arc<BucketService>) -> Router {
162    BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::read_routes(
163        service,
164        "/buckets",
165    )
166}
167
168/// Create Axum router with only the write (mutation) endpoints for Bucket.
169///
170/// These routes must NOT be publicly exposed. Wrap them with an auth
171/// middleware before nesting into the application router.
172///
173/// # This is unguarded generic CRUD, not a validated write path
174///
175/// These are plain create/update/patch/delete mutations over the entity row —
176/// they bypass all business invariants. If the module exposes a validated write
177/// service (e.g. a command router over its domain engine), serve THAT instead
178/// for any mutation that must respect domain rules.
179pub fn create_bucket_write_routes(service: Arc<BucketService>) -> Router {
180    BackboneCrudHandler::<BucketService, Bucket, CreateBucketDto, UpdateBucketDto, BucketResponseDto>::write_routes(
181        service,
182        "/buckets",
183    )
184}
185
186/// Create authenticated routes with auth middleware.
187///
188/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
189/// is responsible for extracting and validating tokens, then providing
190/// an `AuthContext` via request extensions.
191#[cfg(feature = "auth")]
192pub fn create_protected_bucket_routes<A: AuthMiddleware + Send + Sync + 'static>(
193    service: Arc<BucketService>,
194    auth: Arc<A>,
195) -> Router {
196    use axum::middleware;
197    use axum::response::IntoResponse;
198
199    let auth_layer = auth.clone();
200    create_bucket_routes(service)
201        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
202            let auth = auth_layer.clone();
203            async move {
204                let token = req.headers()
205                    .get(axum::http::header::AUTHORIZATION)
206                    .and_then(|h| h.to_str().ok())
207                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
208                    .unwrap_or("");
209                match auth.authenticate(token).await {
210                    Ok(ctx) => {
211                        req.extensions_mut().insert(ctx);
212                        next.run(req).await
213                    }
214                    Err(_) => {
215                        (axum::http::StatusCode::UNAUTHORIZED,
216                         axum::Json(serde_json::json!({
217                             "success": false,
218                             "error": "unauthorized",
219                             "message": "Authentication required"
220                         }))
221                        ).into_response()
222                    }
223                }
224            }
225        }))
226}
227
228// =============================================================================
229// State Transition Handlers
230// =============================================================================
231
232/// Execute lock transition on a Bucket.
233///
234/// POST /buckets/:id/transitions/lock
235pub async fn lock_transition(
236    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
237    axum::extract::Path(id): axum::extract::Path<String>,
238    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
239) -> impl axum::response::IntoResponse {
240    use axum::{http::StatusCode, Json};
241
242    // Get current entity
243    let entity = match service.get_by_id(&id).await {
244        Ok(Some(e)) => e,
245        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
246        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
247    };
248
249    // Check permission (if auth enabled)
250    #[cfg(feature = "auth")]
251    {
252        let allowed_roles = BucketTransition::Lock.allowed_roles();
253        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:lock");
254        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
255        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
256        if !has_specific_perm && !has_role {
257            if !has_update_perm {
258                return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for lock transition")));
259            }
260            tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "lock", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:lock or a role of ["admin", "owner"]");
261        }
262    }
263
264    // Create state machine from entity's actual status and validate transition
265    let current_state: BucketState = match entity.status.to_string().parse() {
266        Ok(s) => s,
267        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
268    };
269    let sm = BucketStateMachine::from_state(current_state);
270    if !sm.can_transition(BucketTransition::Lock) {
271        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
272    }
273
274    // Guard `$actor.id == owner_id || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
275    // Apply transition via partial update
276    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
277    fields.insert("status".to_string(), serde_json::Value::String("readonly".to_string()));
278
279    match backbone_core::write_guard::as_transition("lock", service.partial_update(&id, fields)).await {
280        Ok(Some(updated)) => {
281            let response: BucketResponseDto = updated.into();
282            (StatusCode::OK, Json(ApiResponse::ok(response)))
283        }
284        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
285        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
286    }
287}
288
289/// Execute unlock transition on a Bucket.
290///
291/// POST /buckets/:id/transitions/unlock
292pub async fn unlock_transition(
293    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
294    axum::extract::Path(id): axum::extract::Path<String>,
295    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
296) -> impl axum::response::IntoResponse {
297    use axum::{http::StatusCode, Json};
298
299    // Get current entity
300    let entity = match service.get_by_id(&id).await {
301        Ok(Some(e)) => e,
302        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
303        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
304    };
305
306    // Check permission (if auth enabled)
307    #[cfg(feature = "auth")]
308    {
309        let allowed_roles = BucketTransition::Unlock.allowed_roles();
310        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:unlock");
311        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
312        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
313        if !has_specific_perm && !has_role {
314            if !has_update_perm {
315                return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for unlock transition")));
316            }
317            tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "unlock", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:unlock or a role of ["admin", "owner"]");
318        }
319    }
320
321    // Create state machine from entity's actual status and validate transition
322    let current_state: BucketState = match entity.status.to_string().parse() {
323        Ok(s) => s,
324        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
325    };
326    let sm = BucketStateMachine::from_state(current_state);
327    if !sm.can_transition(BucketTransition::Unlock) {
328        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
329    }
330
331    // Guard `$actor.id == owner_id || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
332    // Apply transition via partial update
333    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
334    fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));
335
336    match backbone_core::write_guard::as_transition("unlock", service.partial_update(&id, fields)).await {
337        Ok(Some(updated)) => {
338            let response: BucketResponseDto = updated.into();
339            (StatusCode::OK, Json(ApiResponse::ok(response)))
340        }
341        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
342        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
343    }
344}
345
346/// Execute archive transition on a Bucket.
347///
348/// POST /buckets/:id/transitions/archive
349pub async fn archive_transition(
350    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
351    axum::extract::Path(id): axum::extract::Path<String>,
352    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
353) -> impl axum::response::IntoResponse {
354    use axum::{http::StatusCode, Json};
355
356    // Get current entity
357    let entity = match service.get_by_id(&id).await {
358        Ok(Some(e)) => e,
359        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
360        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
361    };
362
363    // Check permission (if auth enabled)
364    #[cfg(feature = "auth")]
365    {
366        let allowed_roles = BucketTransition::Archive.allowed_roles();
367        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:archive");
368        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
369        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
370        if !has_specific_perm && !has_role {
371            if !has_update_perm {
372                return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for archive transition")));
373            }
374            tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "archive", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:archive or a role of ["admin", "owner"]");
375        }
376    }
377
378    // Create state machine from entity's actual status and validate transition
379    let current_state: BucketState = match entity.status.to_string().parse() {
380        Ok(s) => s,
381        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
382    };
383    let sm = BucketStateMachine::from_state(current_state);
384    if !sm.can_transition(BucketTransition::Archive) {
385        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
386    }
387
388    // Guard `$actor.id == owner_id || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
389    // Apply transition via partial update
390    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
391    fields.insert("status".to_string(), serde_json::Value::String("archived".to_string()));
392
393    match backbone_core::write_guard::as_transition("archive", service.partial_update(&id, fields)).await {
394        Ok(Some(updated)) => {
395            let response: BucketResponseDto = updated.into();
396            (StatusCode::OK, Json(ApiResponse::ok(response)))
397        }
398        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
399        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
400    }
401}
402
403/// Execute restore transition on a Bucket.
404///
405/// POST /buckets/:id/transitions/restore
406pub async fn restore_transition(
407    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
408    axum::extract::Path(id): axum::extract::Path<String>,
409    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
410) -> impl axum::response::IntoResponse {
411    use axum::{http::StatusCode, Json};
412
413    // Get current entity
414    let entity = match service.get_by_id(&id).await {
415        Ok(Some(e)) => e,
416        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
417        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
418    };
419
420    // Check permission (if auth enabled)
421    #[cfg(feature = "auth")]
422    {
423        let allowed_roles = BucketTransition::Restore.allowed_roles();
424        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:restore");
425        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
426        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
427        if !has_specific_perm && !has_role {
428            if !has_update_perm {
429                return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for restore transition")));
430            }
431            tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "restore", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:restore or a role of ["admin", "owner"]");
432        }
433    }
434
435    // Create state machine from entity's actual status and validate transition
436    let current_state: BucketState = match entity.status.to_string().parse() {
437        Ok(s) => s,
438        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
439    };
440    let sm = BucketStateMachine::from_state(current_state);
441    if !sm.can_transition(BucketTransition::Restore) {
442        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
443    }
444
445    // Guard `$actor.id == owner_id || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
446    // Apply transition via partial update
447    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
448    fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));
449
450    match backbone_core::write_guard::as_transition("restore", service.partial_update(&id, fields)).await {
451        Ok(Some(updated)) => {
452            let response: BucketResponseDto = updated.into();
453            (StatusCode::OK, Json(ApiResponse::ok(response)))
454        }
455        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
456        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
457    }
458}
459
460/// Execute delete transition on a Bucket.
461///
462/// POST /buckets/:id/transitions/delete
463pub async fn delete_transition(
464    axum::extract::State(service): axum::extract::State<Arc<BucketService>>,
465    axum::extract::Path(id): axum::extract::Path<String>,
466    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
467) -> impl axum::response::IntoResponse {
468    use axum::{http::StatusCode, Json};
469
470    // Get current entity
471    let entity = match service.get_by_id(&id).await {
472        Ok(Some(e)) => e,
473        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
474        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
475    };
476
477    // Check permission (if auth enabled)
478    #[cfg(feature = "auth")]
479    {
480        let allowed_roles = BucketTransition::Delete.allowed_roles();
481        let has_specific_perm = auth.permissions.iter().any(|p| p == "bucket:transition:delete");
482        let has_update_perm = auth.permissions.iter().any(|p| p == "bucket:update");
483        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
484        if !has_specific_perm && !has_role {
485            if !has_update_perm {
486                return (StatusCode::FORBIDDEN, Json(ApiResponse::<BucketResponseDto>::error("Insufficient permissions for delete transition")));
487            }
488            tracing::warn!(target: "backbone::write_guard", entity = "Bucket", verb = "delete", code = "transition_by_update_permission", "a transition granted only by bucket:update, running in shadow; it needs bucket:transition:delete or a role of ["admin", "owner"]");
489        }
490    }
491
492    // Create state machine from entity's actual status and validate transition
493    let current_state: BucketState = match entity.status.to_string().parse() {
494        Ok(s) => s,
495        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<BucketResponseDto>::error("The stored state is not a state of this machine"))),
496    };
497    let sm = BucketStateMachine::from_state(current_state);
498    if !sm.can_transition(BucketTransition::Delete) {
499        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<BucketResponseDto>::error("Transition not allowed from current state")));
500    }
501
502    // Guard `file_count == 0 || $actor.has_role('admin')` not compiled (reads the writer, the time or the row before the write); the transition is not checked against it.
503    // Apply transition via partial update
504    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
505    fields.insert("status".to_string(), serde_json::Value::String("deleted".to_string()));
506
507    match backbone_core::write_guard::as_transition("delete", service.partial_update(&id, fields)).await {
508        Ok(Some(updated)) => {
509            let response: BucketResponseDto = updated.into();
510            (StatusCode::OK, Json(ApiResponse::ok(response)))
511        }
512        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<BucketResponseDto>::not_found("Bucket", &id))),
513        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BucketResponseDto>::error(e.to_string()))),
514    }
515}
516
517/// Create routes for state transitions.
518pub fn create_bucket_transition_routes(service: Arc<BucketService>) -> Router {
519    use axum::routing::post;
520
521    Router::new()
522        .route("/buckets/:id/transitions/lock", post(lock_transition))
523        .route("/buckets/:id/transitions/unlock", post(unlock_transition))
524        .route("/buckets/:id/transitions/archive", post(archive_transition))
525        .route("/buckets/:id/transitions/restore", post(restore_transition))
526        .route("/buckets/:id/transitions/delete", post(delete_transition))
527        .with_state(service)
528}
529