use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use room::ws_context::WsUserContext;
use service::AppService;
use session::Session;
use uuid::Uuid;

#[utoipa::path(
    get,
    path = "/api/rooms/{room_id}/messages/{message_id}/edit-history",
    params(
        ("room_id" = Uuid, Path),
        ("message_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "Get message edit history", body = ApiResponse<room::MessageEditHistoryResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn message_edit_history(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(Uuid, Uuid)>,
) -> Result<HttpResponse, ApiError> {
    let (_room_id, message_id) = path.into_inner();
    let user_id = session
        .user()
        .ok_or_else(|| ApiError::from(service::error::AppError::Unauthorized))?;
    let ctx = WsUserContext::new(user_id);
    let resp = service
        .room
        .get_message_edit_history(message_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[derive(Debug, serde::Deserialize)]
pub struct MentionQuery {
    pub limit: Option<u64>,
}

#[utoipa::path(
    get,
    path = "/api/me/mentions",
    params(
        ("limit" = Option<u64>, Query),
    ),
    responses(
        (status = 200, description = "List mentions", body = ApiResponse<Vec<room::MentionNotificationResponse>>),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Room"
)]
pub async fn mention_list(
    service: web::Data<AppService>,
    session: Session,
    query: web::Query<MentionQuery>,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or_else(|| ApiError::from(service::error::AppError::Unauthorized))?;
    let ctx = WsUserContext::new(user_id);
    let resp = service
        .room
        .get_mention_notifications(query.limit, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/me/mentions/read-all",
    responses(
        (status = 200, description = "Mark all mentions as read"),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Room"
)]
pub async fn mention_read_all(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or_else(|| ApiError::from(service::error::AppError::Unauthorized))?;
    let ctx = WsUserContext::new(user_id);
    service
        .room
        .mark_mention_notifications_read(&ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(true).to_response())
}
