use axum::Json;
use axum::extract::FromRef;
use axum::extract::{Extension, Path, Query, State};
use uuid::Uuid;

use erp_core::error::AppError;
use erp_core::rbac::require_permission;
use erp_core::types::{ApiResponse, PaginatedResponse, TenantContext};
use validator::Validate;

use crate::dto::{MessageQuery, MessageResp, SendMessageReq, UnreadCountResp};
use crate::message_state::MessageState;
use crate::service::message_service::MessageService;

#[utoipa::path(
    get,
    path = "/api/v1/messages",
    params(MessageQuery),
    responses(
        (status = 200, description = "成功", body = ApiResponse<PaginatedResponse<MessageResp>>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息管理"
)]
/// 查询消息列表。
pub async fn list_messages<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
    Query(query): Query<MessageQuery>,
) -> Result<Json<ApiResponse<PaginatedResponse<MessageResp>>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "message.list")?;

    let db = &_state.db;
    let page = query.page.unwrap_or(1);
    let page_size = query.page_size.unwrap_or(20);

    let (messages, total) = MessageService::list(ctx.tenant_id, ctx.user_id, &query, db).await?;

    let total_pages = total.div_ceil(page_size);
    Ok(Json(ApiResponse::ok(PaginatedResponse {
        data: messages,
        total,
        page,
        page_size,
        total_pages,
    })))
}

#[utoipa::path(
    get,
    path = "/api/v1/messages/unread-count",
    responses(
        (status = 200, description = "成功", body = ApiResponse<UnreadCountResp>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息管理"
)]
/// 获取未读消息数量。
pub async fn unread_count<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
) -> Result<Json<ApiResponse<UnreadCountResp>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "message.list")?;

    let result = MessageService::unread_count(ctx.tenant_id, ctx.user_id, &_state.db).await?;
    Ok(Json(ApiResponse::ok(result)))
}

#[utoipa::path(
    post,
    path = "/api/v1/messages",
    request_body = SendMessageReq,
    responses(
        (status = 200, description = "成功", body = ApiResponse<MessageResp>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息管理"
)]
/// 发送消息。
pub async fn send_message<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
    Json(req): Json<SendMessageReq>,
) -> Result<Json<ApiResponse<MessageResp>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "message.send")?;

    req.validate()
        .map_err(|e| AppError::Validation(e.to_string()))?;

    let resp = MessageService::send(
        ctx.tenant_id,
        ctx.user_id,
        &req,
        &_state.db,
        &_state.event_bus,
    )
    .await?;

    Ok(Json(ApiResponse::ok(resp)))
}

#[utoipa::path(
    put,
    path = "/api/v1/messages/{id}/read",
    params(("id" = Uuid, Path, description = "消息ID")),
    responses(
        (status = 200, description = "成功"),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息管理"
)]
/// 标记消息已读。
pub async fn mark_read<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
    Path(id): Path<Uuid>,
) -> Result<Json<ApiResponse<()>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    MessageService::mark_read(id, ctx.tenant_id, ctx.user_id, &_state.db).await?;
    Ok(Json(ApiResponse::ok(())))
}

#[utoipa::path(
    put,
    path = "/api/v1/messages/read-all",
    responses(
        (status = 200, description = "成功"),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息管理"
)]
/// 标记所有消息已读。
pub async fn mark_all_read<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
) -> Result<Json<ApiResponse<()>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    MessageService::mark_all_read(ctx.tenant_id, ctx.user_id, &_state.db).await?;
    Ok(Json(ApiResponse::ok(())))
}

#[utoipa::path(
    delete,
    path = "/api/v1/messages/{id}",
    params(("id" = Uuid, Path, description = "消息ID")),
    responses(
        (status = 200, description = "成功"),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息管理"
)]
/// 删除消息。
pub async fn delete_message<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
    Path(id): Path<Uuid>,
) -> Result<Json<ApiResponse<()>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    MessageService::delete(id, ctx.tenant_id, ctx.user_id, &_state.db).await?;
    Ok(Json(ApiResponse::ok(())))
}
