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::BackboneCrudHandler;
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;
use crate::domain::entity::*;
use crate::application::service::{DiscussChannelMemberService, ServiceError};
use crate::presentation::dto::{CreateDiscussChannelMemberDto, UpdateDiscussChannelMemberDto, PatchDiscussChannelMemberDto, DiscussChannelMemberResponseDto};
#[derive(Debug, thiserror::Error)]
pub enum DiscussChannelMemberError {
#[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 channel member must be a partner or a guest (CHECK partner_id IS NOT NULL OR guest_id IS NOT NULL — fires on raw SQL).: {0}")]
DiscussChannelMemberPersonaMissing(String),
#[error("One member row per (channel, partner/guest) — enforced by the two partial unique indexes declared on the model.: {0}")]
DiscussChannelMemberDuplicate(String),
}
impl From<ServiceError> for DiscussChannelMemberError {
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 DiscussChannelMemberError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "DISCUSSCHANNELMEMBER_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "DISCUSSCHANNELMEMBER_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "DISCUSSCHANNELMEMBER_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "DISCUSSCHANNELMEMBER_INTERNAL_ERROR"),
Self::DiscussChannelMemberPersonaMissing(_) => (StatusCode::UNPROCESSABLE_ENTITY, "DISCUSSCHANNELMEMBER_DISCUSS_CHANNEL_MEMBER_PERSONA_MISSING"),
Self::DiscussChannelMemberDuplicate(_) => (StatusCode::UNPROCESSABLE_ENTITY, "DISCUSSCHANNELMEMBER_DISCUSS_CHANNEL_MEMBER_DUPLICATE"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod discuss_channel_member_errors {
pub const DISCUSS_CHANNEL_MEMBER_PERSONA_MISSING: &str = "DISCUSSCHANNELMEMBER_DISCUSS_CHANNEL_MEMBER_PERSONA_MISSING";
pub const DISCUSS_CHANNEL_MEMBER_DUPLICATE: &str = "DISCUSSCHANNELMEMBER_DISCUSS_CHANNEL_MEMBER_DUPLICATE";
}
pub fn create_discuss_channel_member_routes(service: Arc<DiscussChannelMemberService>) -> Router {
BackboneCrudHandler::<DiscussChannelMemberService, DiscussChannelMember, CreateDiscussChannelMemberDto, UpdateDiscussChannelMemberDto, DiscussChannelMemberResponseDto>::routes(
service,
"/discuss_channel_members",
)
}
pub fn create_discuss_channel_member_read_routes(service: Arc<DiscussChannelMemberService>) -> Router {
BackboneCrudHandler::<DiscussChannelMemberService, DiscussChannelMember, CreateDiscussChannelMemberDto, UpdateDiscussChannelMemberDto, DiscussChannelMemberResponseDto>::read_routes(
service,
"/discuss_channel_members",
)
}
pub fn create_discuss_channel_member_write_routes(service: Arc<DiscussChannelMemberService>) -> Router {
BackboneCrudHandler::<DiscussChannelMemberService, DiscussChannelMember, CreateDiscussChannelMemberDto, UpdateDiscussChannelMemberDto, DiscussChannelMemberResponseDto>::write_routes(
service,
"/discuss_channel_members",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_discuss_channel_member_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<DiscussChannelMemberService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_discuss_channel_member_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()
}
}
}
}))
}