Skip to main content

backbone_bucket/presentation/http/
file_comment_handler.rs

1//! FileComment 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;
13use chrono::{DateTime, Utc};
14
15// Backbone framework imports
16use backbone_core::http::{ApiResponse, BackboneCrudHandler};
17
18// Auth integration (optional)
19#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24// Domain imports
25use crate::domain::entity::*;
26use crate::application::service::{FileCommentService, ServiceError};
27
28// DTO imports
29use crate::presentation::dto::{CreateFileCommentDto, UpdateFileCommentDto, PatchFileCommentDto, FileCommentResponseDto};
30
31use crate::domain::state_machine::{FileCommentState, FileCommentStateMachine, FileCommentTransition};
32
33/// Application error type
34#[derive(Debug, thiserror::Error)]
35pub enum FileCommentError {
36    #[error("Not found: {0}")]
37    NotFound(String),
38    #[error("Validation error: {0}")]
39    Validation(String),
40    #[error("Database error: {0}")]
41    Database(String),
42    #[error("Internal error: {0}")]
43    Internal(String),
44    // Domain-specific errors from hook rules
45    #[error("File must exist: {0}")]
46    FileNotFound(String),
47    #[error("File must be accessible: {0}")]
48    FileNotAccessible(String),
49    #[error("Comment content is required: {0}")]
50    EmptyComment(String),
51    #[error("Comment content max 10000 characters: {0}")]
52    CommentTooLong(String),
53    #[error("Parent comment must exist if provided: {0}")]
54    InvalidParentComment(String),
55    #[error("All mentioned users must exist: {0}")]
56    InvalidMention(String),
57    #[error("Annotation region must be valid JSON: {0}")]
58    InvalidAnnotation(String),
59    #[error("Only comment owner can edit: {0}")]
60    NotCommentOwner(String),
61    #[error("Cannot edit deleted comment: {0}")]
62    CommentDeleted(String),
63    #[error("Cannot edit resolved comment after 5 minutes: {0}")]
64    EditTimeout(String),
65    #[error("Maximum thread depth exceeded: {0}")]
66    MaxThreadDepthExceeded(String),
67}
68
69impl From<ServiceError> for FileCommentError {
70    fn from(err: ServiceError) -> Self {
71        match err {
72            ServiceError::NotFound => Self::NotFound(err.to_string()),
73            ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
74            ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
75            ServiceError::Repository(ref e) => Self::Database(e.to_string()),
76            ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
77            ServiceError::Violations(_) => Self::Validation(err.to_string()),
78        }
79    }
80}
81
82impl axum::response::IntoResponse for FileCommentError {
83    fn into_response(self) -> axum::response::Response {
84        use axum::http::StatusCode;
85        use axum::Json;
86
87        let (status, code) = match &self {
88            Self::NotFound(_) => (StatusCode::NOT_FOUND, "FILECOMMENT_NOT_FOUND"),
89            Self::Validation(_) => (StatusCode::BAD_REQUEST, "FILECOMMENT_VALIDATION_ERROR"),
90            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILECOMMENT_DATABASE_ERROR"),
91            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILECOMMENT_INTERNAL_ERROR"),
92            Self::FileNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_FILE_NOT_FOUND"),
93            Self::FileNotAccessible(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_FILE_NOT_ACCESSIBLE"),
94            Self::EmptyComment(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_EMPTY_COMMENT"),
95            Self::CommentTooLong(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_COMMENT_TOO_LONG"),
96            Self::InvalidParentComment(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_PARENT_COMMENT"),
97            Self::InvalidMention(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_MENTION"),
98            Self::InvalidAnnotation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_ANNOTATION"),
99            Self::NotCommentOwner(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_NOT_COMMENT_OWNER"),
100            Self::CommentDeleted(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_COMMENT_DELETED"),
101            Self::EditTimeout(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_EDIT_TIMEOUT"),
102            Self::MaxThreadDepthExceeded(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_MAX_THREAD_DEPTH_EXCEEDED"),
103        };
104
105        let body = serde_json::json!({
106            "success": false,
107            "error": code,
108            "message": self.to_string(),
109        });
110
111        (status, Json(body)).into_response()
112    }
113}
114
115/// Domain-specific error codes for FileComment
116pub mod file_comment_errors {
117    pub const FILE_NOT_FOUND: &str = "FILECOMMENT_FILE_NOT_FOUND";
118    pub const FILE_NOT_ACCESSIBLE: &str = "FILECOMMENT_FILE_NOT_ACCESSIBLE";
119    pub const EMPTY_COMMENT: &str = "FILECOMMENT_EMPTY_COMMENT";
120    pub const COMMENT_TOO_LONG: &str = "FILECOMMENT_COMMENT_TOO_LONG";
121    pub const INVALID_PARENT_COMMENT: &str = "FILECOMMENT_INVALID_PARENT_COMMENT";
122    pub const INVALID_MENTION: &str = "FILECOMMENT_INVALID_MENTION";
123    pub const INVALID_ANNOTATION: &str = "FILECOMMENT_INVALID_ANNOTATION";
124    pub const NOT_COMMENT_OWNER: &str = "FILECOMMENT_NOT_COMMENT_OWNER";
125    pub const COMMENT_DELETED: &str = "FILECOMMENT_COMMENT_DELETED";
126    pub const EDIT_TIMEOUT: &str = "FILECOMMENT_EDIT_TIMEOUT";
127    pub const MAX_THREAD_DEPTH_EXCEEDED: &str = "FILECOMMENT_MAX_THREAD_DEPTH_EXCEEDED";
128}
129
130// =============================================================================
131// Route Configuration
132// =============================================================================
133
134/// Create Axum router with all 16 Backbone endpoints for FileComment.
135///
136/// # Routes
137///
138/// | Method | Path | Description |
139/// |--------|------|-------------|
140/// | GET | /file_comments | List with pagination |
141/// | POST | /file_comments | Create new |
142/// | GET | /file_comments/:id | Get by ID |
143/// | PUT | /file_comments/:id | Full update |
144/// | PATCH | /file_comments/:id | Partial update |
145/// | DELETE | /file_comments/:id | Soft delete |
146/// | POST | /file_comments/bulk | Bulk create |
147/// | POST | /file_comments/upsert | Upsert |
148/// | GET | /file_comments/trash | List deleted |
149/// | POST | /file_comments/:id/restore | Restore |
150/// | DELETE | /file_comments/empty | Empty trash |
151/// | GET | /file_comments/:id/deleted | Get deleted by ID |
152/// | DELETE | /file_comments/trash/:id | Permanent delete from trash |
153/// | GET | /file_comments/count | Count active entities |
154/// | GET | /file_comments/trash/count | Count deleted entities |
155///
156/// # Example
157///
158/// ```text
159/// let service = Arc::new(FileCommentService::with_repository(repository));
160/// let router = create_file_comment_routes(service);
161/// ```
162pub fn create_file_comment_routes(service: Arc<FileCommentService>) -> Router {
163    BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::routes(
164        service,
165        "/file_comments",
166    )
167}
168
169/// Create Axum router with only the read (GET) endpoints for FileComment.
170///
171/// Safe for public, unauthenticated exposure (e.g., reference data).
172/// Mutations must be served separately via `create_file_comment_write_routes`,
173/// typically wrapped in an auth middleware layer.
174pub fn create_file_comment_read_routes(service: Arc<FileCommentService>) -> Router {
175    BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::read_routes(
176        service,
177        "/file_comments",
178    )
179}
180
181/// Create Axum router with only the write (mutation) endpoints for FileComment.
182///
183/// These routes must NOT be publicly exposed. Wrap them with an auth
184/// middleware before nesting into the application router.
185///
186/// # This is unguarded generic CRUD, not a validated write path
187///
188/// These are plain create/update/patch/delete mutations over the entity row —
189/// they bypass all business invariants. If the module exposes a validated write
190/// service (e.g. a command router over its domain engine), serve THAT instead
191/// for any mutation that must respect domain rules.
192pub fn create_file_comment_write_routes(service: Arc<FileCommentService>) -> Router {
193    BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::write_routes(
194        service,
195        "/file_comments",
196    )
197}
198
199/// Create authenticated routes with auth middleware.
200///
201/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
202/// is responsible for extracting and validating tokens, then providing
203/// an `AuthContext` via request extensions.
204#[cfg(feature = "auth")]
205pub fn create_protected_file_comment_routes<A: AuthMiddleware + Send + Sync + 'static>(
206    service: Arc<FileCommentService>,
207    auth: Arc<A>,
208) -> Router {
209    use axum::middleware;
210    use axum::response::IntoResponse;
211
212    let auth_layer = auth.clone();
213    create_file_comment_routes(service)
214        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
215            let auth = auth_layer.clone();
216            async move {
217                let token = req.headers()
218                    .get(axum::http::header::AUTHORIZATION)
219                    .and_then(|h| h.to_str().ok())
220                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
221                    .unwrap_or("");
222                match auth.authenticate(token).await {
223                    Ok(ctx) => {
224                        req.extensions_mut().insert(ctx);
225                        next.run(req).await
226                    }
227                    Err(_) => {
228                        (axum::http::StatusCode::UNAUTHORIZED,
229                         axum::Json(serde_json::json!({
230                             "success": false,
231                             "error": "unauthorized",
232                             "message": "Authentication required"
233                         }))
234                        ).into_response()
235                    }
236                }
237            }
238        }))
239}
240
241// =============================================================================
242// State Transition Handlers
243// =============================================================================
244
245/// Execute resolve transition on a FileComment.
246///
247/// POST /file_comments/:id/transitions/resolve
248pub async fn resolve_transition(
249    axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
250    axum::extract::Path(id): axum::extract::Path<String>,
251    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
252) -> impl axum::response::IntoResponse {
253    use axum::{http::StatusCode, Json};
254
255    // Get current entity
256    let entity = match service.get_by_id(&id).await {
257        Ok(Some(e)) => e,
258        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
259        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
260    };
261
262    // Check permission (if auth enabled)
263    #[cfg(feature = "auth")]
264    {
265        let allowed_roles = FileCommentTransition::Resolve.allowed_roles();
266        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:resolve");
267        let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
268        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
269        if !has_specific_perm && !has_update_perm && !has_role {
270            return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for resolve transition")));
271        }
272    }
273
274    // Create state machine from entity's actual status and validate transition
275    let current_state: FileCommentState = entity.status.to_string().parse()
276        .unwrap_or(FileCommentState::default());
277    let sm = FileCommentStateMachine::from_state(current_state);
278    if !sm.can_transition(FileCommentTransition::Resolve) {
279        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
280    }
281
282    // Apply transition via partial update
283    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
284    fields.insert("status".to_string(), serde_json::Value::String("Resolved".to_string()));
285
286    match service.partial_update(&id, fields).await {
287        Ok(Some(updated)) => {
288            let response: FileCommentResponseDto = updated.into();
289            (StatusCode::OK, Json(ApiResponse::ok(response)))
290        }
291        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
292        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
293    }
294}
295
296/// Execute edit transition on a FileComment.
297///
298/// POST /file_comments/:id/transitions/edit
299pub async fn edit_transition(
300    axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
301    axum::extract::Path(id): axum::extract::Path<String>,
302    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
303) -> impl axum::response::IntoResponse {
304    use axum::{http::StatusCode, Json};
305
306    // Get current entity
307    let entity = match service.get_by_id(&id).await {
308        Ok(Some(e)) => e,
309        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
310        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
311    };
312
313    // Check permission (if auth enabled)
314    #[cfg(feature = "auth")]
315    {
316        let allowed_roles = FileCommentTransition::Edit.allowed_roles();
317        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:edit");
318        let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
319        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
320        if !has_specific_perm && !has_update_perm && !has_role {
321            return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for edit transition")));
322        }
323    }
324
325    // Create state machine from entity's actual status and validate transition
326    let current_state: FileCommentState = entity.status.to_string().parse()
327        .unwrap_or(FileCommentState::default());
328    let sm = FileCommentStateMachine::from_state(current_state);
329    if !sm.can_transition(FileCommentTransition::Edit) {
330        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
331    }
332
333    // Apply transition via partial update
334    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
335    fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
336
337    match service.partial_update(&id, fields).await {
338        Ok(Some(updated)) => {
339            let response: FileCommentResponseDto = updated.into();
340            (StatusCode::OK, Json(ApiResponse::ok(response)))
341        }
342        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
343        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
344    }
345}
346
347/// Execute delete_active transition on a FileComment.
348///
349/// POST /file_comments/:id/transitions/delete_active
350pub async fn delete_active_transition(
351    axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
352    axum::extract::Path(id): axum::extract::Path<String>,
353    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
354) -> impl axum::response::IntoResponse {
355    use axum::{http::StatusCode, Json};
356
357    // Get current entity
358    let entity = match service.get_by_id(&id).await {
359        Ok(Some(e)) => e,
360        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
361        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
362    };
363
364    // Check permission (if auth enabled)
365    #[cfg(feature = "auth")]
366    {
367        let allowed_roles = FileCommentTransition::DeleteActive.allowed_roles();
368        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:delete_active");
369        let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
370        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
371        if !has_specific_perm && !has_update_perm && !has_role {
372            return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for delete_active transition")));
373        }
374    }
375
376    // Create state machine from entity's actual status and validate transition
377    let current_state: FileCommentState = entity.status.to_string().parse()
378        .unwrap_or(FileCommentState::default());
379    let sm = FileCommentStateMachine::from_state(current_state);
380    if !sm.can_transition(FileCommentTransition::DeleteActive) {
381        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
382    }
383
384    // Apply transition via partial update
385    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
386    fields.insert("status".to_string(), serde_json::Value::String("Deleted".to_string()));
387
388    match service.partial_update(&id, fields).await {
389        Ok(Some(updated)) => {
390            let response: FileCommentResponseDto = updated.into();
391            (StatusCode::OK, Json(ApiResponse::ok(response)))
392        }
393        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
394        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
395    }
396}
397
398/// Execute reopen transition on a FileComment.
399///
400/// POST /file_comments/:id/transitions/reopen
401pub async fn reopen_transition(
402    axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
403    axum::extract::Path(id): axum::extract::Path<String>,
404    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
405) -> impl axum::response::IntoResponse {
406    use axum::{http::StatusCode, Json};
407
408    // Get current entity
409    let entity = match service.get_by_id(&id).await {
410        Ok(Some(e)) => e,
411        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
412        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
413    };
414
415    // Check permission (if auth enabled)
416    #[cfg(feature = "auth")]
417    {
418        let allowed_roles = FileCommentTransition::Reopen.allowed_roles();
419        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:reopen");
420        let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
421        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
422        if !has_specific_perm && !has_update_perm && !has_role {
423            return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for reopen transition")));
424        }
425    }
426
427    // Create state machine from entity's actual status and validate transition
428    let current_state: FileCommentState = entity.status.to_string().parse()
429        .unwrap_or(FileCommentState::default());
430    let sm = FileCommentStateMachine::from_state(current_state);
431    if !sm.can_transition(FileCommentTransition::Reopen) {
432        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
433    }
434
435    // Apply transition via partial update
436    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
437    fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
438
439    match service.partial_update(&id, fields).await {
440        Ok(Some(updated)) => {
441            let response: FileCommentResponseDto = updated.into();
442            (StatusCode::OK, Json(ApiResponse::ok(response)))
443        }
444        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
445        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
446    }
447}
448
449/// Execute delete_resolved transition on a FileComment.
450///
451/// POST /file_comments/:id/transitions/delete_resolved
452pub async fn delete_resolved_transition(
453    axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
454    axum::extract::Path(id): axum::extract::Path<String>,
455    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
456) -> impl axum::response::IntoResponse {
457    use axum::{http::StatusCode, Json};
458
459    // Get current entity
460    let entity = match service.get_by_id(&id).await {
461        Ok(Some(e)) => e,
462        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
463        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
464    };
465
466    // Check permission (if auth enabled)
467    #[cfg(feature = "auth")]
468    {
469        let allowed_roles = FileCommentTransition::DeleteResolved.allowed_roles();
470        let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:delete_resolved");
471        let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
472        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
473        if !has_specific_perm && !has_update_perm && !has_role {
474            return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for delete_resolved transition")));
475        }
476    }
477
478    // Create state machine from entity's actual status and validate transition
479    let current_state: FileCommentState = entity.status.to_string().parse()
480        .unwrap_or(FileCommentState::default());
481    let sm = FileCommentStateMachine::from_state(current_state);
482    if !sm.can_transition(FileCommentTransition::DeleteResolved) {
483        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
484    }
485
486    // Apply transition via partial update
487    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
488    fields.insert("status".to_string(), serde_json::Value::String("Deleted".to_string()));
489
490    match service.partial_update(&id, fields).await {
491        Ok(Some(updated)) => {
492            let response: FileCommentResponseDto = updated.into();
493            (StatusCode::OK, Json(ApiResponse::ok(response)))
494        }
495        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
496        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
497    }
498}
499
500/// Create routes for state transitions.
501pub fn create_file_comment_transition_routes(service: Arc<FileCommentService>) -> Router {
502    use axum::routing::post;
503
504    Router::new()
505        .route("/file_comments/:id/transitions/resolve", post(resolve_transition))
506        .route("/file_comments/:id/transitions/edit", post(edit_transition))
507        .route("/file_comments/:id/transitions/delete_active", post(delete_active_transition))
508        .route("/file_comments/:id/transitions/reopen", post(reopen_transition))
509        .route("/file_comments/:id/transitions/delete_resolved", post(delete_resolved_transition))
510        .with_state(service)
511}