use axum::Json;
use axum::extract::FromRef;
use axum::extract::{Extension, State};

use erp_core::error::AppError;
use erp_core::types::{ApiResponse, TenantContext};

use crate::dto::UpdateSubscriptionReq;
use crate::message_state::MessageState;
use crate::service::subscription_service::SubscriptionService;

#[utoipa::path(
    get,
    path = "/api/v1/message-subscriptions",
    responses(
        (status = 200, description = "成功", body = ApiResponse<crate::dto::MessageSubscriptionResp>),
        (status = 401, description = "未授权"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息订阅"
)]
/// 获取当前用户的消息订阅偏好。
pub async fn get_subscription<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
) -> Result<Json<ApiResponse<crate::dto::MessageSubscriptionResp>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    let resp = SubscriptionService::get(ctx.tenant_id, ctx.user_id, &_state.db).await?;
    Ok(Json(ApiResponse::ok(resp)))
}

#[utoipa::path(
    put,
    path = "/api/v1/message-subscriptions",
    request_body = UpdateSubscriptionReq,
    responses(
        (status = 200, description = "成功", body = ApiResponse<crate::dto::MessageSubscriptionResp>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "消息订阅"
)]
/// 更新消息订阅偏好。
pub async fn update_subscription<S>(
    State(_state): State<MessageState>,
    Extension(ctx): Extension<TenantContext>,
    Json(req): Json<UpdateSubscriptionReq>,
) -> Result<Json<ApiResponse<crate::dto::MessageSubscriptionResp>>, AppError>
where
    MessageState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    let resp = SubscriptionService::upsert(ctx.tenant_id, ctx.user_id, &req, &_state.db).await?;

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