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::{FileCommentService, ServiceError};
use crate::presentation::dto::{CreateFileCommentDto, UpdateFileCommentDto, PatchFileCommentDto, FileCommentResponseDto};
use crate::domain::state_machine::{FileCommentState, FileCommentStateMachine, FileCommentTransition};
#[derive(Debug, thiserror::Error)]
pub enum FileCommentError {
#[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("File must exist: {0}")]
FileNotFound(String),
#[error("File must be accessible: {0}")]
FileNotAccessible(String),
#[error("Comment content is required: {0}")]
EmptyComment(String),
#[error("Comment content max 10000 characters: {0}")]
CommentTooLong(String),
#[error("Parent comment must exist if provided: {0}")]
InvalidParentComment(String),
#[error("All mentioned users must exist: {0}")]
InvalidMention(String),
#[error("Annotation region must be valid JSON: {0}")]
InvalidAnnotation(String),
#[error("Only comment owner can edit: {0}")]
NotCommentOwner(String),
#[error("Cannot edit deleted comment: {0}")]
CommentDeleted(String),
#[error("Cannot edit resolved comment after 5 minutes: {0}")]
EditTimeout(String),
#[error("Maximum thread depth exceeded: {0}")]
MaxThreadDepthExceeded(String),
}
impl From<ServiceError> for FileCommentError {
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 FileCommentError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "FILECOMMENT_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "FILECOMMENT_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILECOMMENT_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILECOMMENT_INTERNAL_ERROR"),
Self::FileNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_FILE_NOT_FOUND"),
Self::FileNotAccessible(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_FILE_NOT_ACCESSIBLE"),
Self::EmptyComment(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_EMPTY_COMMENT"),
Self::CommentTooLong(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_COMMENT_TOO_LONG"),
Self::InvalidParentComment(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_PARENT_COMMENT"),
Self::InvalidMention(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_MENTION"),
Self::InvalidAnnotation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_ANNOTATION"),
Self::NotCommentOwner(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_NOT_COMMENT_OWNER"),
Self::CommentDeleted(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_COMMENT_DELETED"),
Self::EditTimeout(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_EDIT_TIMEOUT"),
Self::MaxThreadDepthExceeded(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_MAX_THREAD_DEPTH_EXCEEDED"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod file_comment_errors {
pub const FILE_NOT_FOUND: &str = "FILECOMMENT_FILE_NOT_FOUND";
pub const FILE_NOT_ACCESSIBLE: &str = "FILECOMMENT_FILE_NOT_ACCESSIBLE";
pub const EMPTY_COMMENT: &str = "FILECOMMENT_EMPTY_COMMENT";
pub const COMMENT_TOO_LONG: &str = "FILECOMMENT_COMMENT_TOO_LONG";
pub const INVALID_PARENT_COMMENT: &str = "FILECOMMENT_INVALID_PARENT_COMMENT";
pub const INVALID_MENTION: &str = "FILECOMMENT_INVALID_MENTION";
pub const INVALID_ANNOTATION: &str = "FILECOMMENT_INVALID_ANNOTATION";
pub const NOT_COMMENT_OWNER: &str = "FILECOMMENT_NOT_COMMENT_OWNER";
pub const COMMENT_DELETED: &str = "FILECOMMENT_COMMENT_DELETED";
pub const EDIT_TIMEOUT: &str = "FILECOMMENT_EDIT_TIMEOUT";
pub const MAX_THREAD_DEPTH_EXCEEDED: &str = "FILECOMMENT_MAX_THREAD_DEPTH_EXCEEDED";
}
pub fn create_file_comment_routes(service: Arc<FileCommentService>) -> Router {
BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::routes(
service,
"/file_comments",
)
}
pub fn create_file_comment_read_routes(service: Arc<FileCommentService>) -> Router {
BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::read_routes(
service,
"/file_comments",
)
}
pub fn create_file_comment_write_routes(service: Arc<FileCommentService>) -> Router {
BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::write_routes(
service,
"/file_comments",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_file_comment_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<FileCommentService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_file_comment_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 resolve_transition(
axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
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::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileCommentTransition::Resolve.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:resolve");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment: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::<FileCommentResponseDto>::error("Insufficient permissions for resolve transition")));
}
}
let current_state: FileCommentState = entity.status.to_string().parse()
.unwrap_or(FileCommentState::default());
let sm = FileCommentStateMachine::from_state(current_state);
if !sm.can_transition(FileCommentTransition::Resolve) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Resolved".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileCommentResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
}
}
pub async fn edit_transition(
axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
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::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileCommentTransition::Edit.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:edit");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment: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::<FileCommentResponseDto>::error("Insufficient permissions for edit transition")));
}
}
let current_state: FileCommentState = entity.status.to_string().parse()
.unwrap_or(FileCommentState::default());
let sm = FileCommentStateMachine::from_state(current_state);
if !sm.can_transition(FileCommentTransition::Edit) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileCommentResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
}
}
pub async fn delete_active_transition(
axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
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::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileCommentTransition::DeleteActive.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:delete_active");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment: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::<FileCommentResponseDto>::error("Insufficient permissions for delete_active transition")));
}
}
let current_state: FileCommentState = entity.status.to_string().parse()
.unwrap_or(FileCommentState::default());
let sm = FileCommentStateMachine::from_state(current_state);
if !sm.can_transition(FileCommentTransition::DeleteActive) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Deleted".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileCommentResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
}
}
pub async fn reopen_transition(
axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
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::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileCommentTransition::Reopen.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:reopen");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment: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::<FileCommentResponseDto>::error("Insufficient permissions for reopen transition")));
}
}
let current_state: FileCommentState = entity.status.to_string().parse()
.unwrap_or(FileCommentState::default());
let sm = FileCommentStateMachine::from_state(current_state);
if !sm.can_transition(FileCommentTransition::Reopen) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Active".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileCommentResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
}
}
pub async fn delete_resolved_transition(
axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
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::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = FileCommentTransition::DeleteResolved.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:delete_resolved");
let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment: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::<FileCommentResponseDto>::error("Insufficient permissions for delete_resolved transition")));
}
}
let current_state: FileCommentState = entity.status.to_string().parse()
.unwrap_or(FileCommentState::default());
let sm = FileCommentStateMachine::from_state(current_state);
if !sm.can_transition(FileCommentTransition::DeleteResolved) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Deleted".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: FileCommentResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
}
}
pub fn create_file_comment_transition_routes(service: Arc<FileCommentService>) -> Router {
use axum::routing::post;
Router::new()
.route("/file_comments/:id/transitions/resolve", post(resolve_transition))
.route("/file_comments/:id/transitions/edit", post(edit_transition))
.route("/file_comments/:id/transitions/delete_active", post(delete_active_transition))
.route("/file_comments/:id/transitions/reopen", post(reopen_transition))
.route("/file_comments/:id/transitions/delete_resolved", post(delete_resolved_transition))
.with_state(service)
}