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

#[derive(Debug, serde::Deserialize, IntoParams)]
pub struct MessageListQuery {
    pub before_seq: Option<i64>,
    pub after_seq: Option<i64>,
    pub limit: Option<u64>,
}

#[utoipa::path(
    get,
    path = "/api/rooms/{room_id}/messages",
    params(
        ("room_id" = Uuid, Path),
        ("before_seq" = Option<i64>, Query),
        ("after_seq" = Option<i64>, Query),
        ("limit" = Option<u64>, Query),
    ),
    responses(
        (status = 200, description = "List room messages", body = ApiResponse<room::RoomMessageListResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn message_list(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<Uuid>,
    query: web::Query<MessageListQuery>,
) -> Result<HttpResponse, ApiError> {
    let room_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
        .room_message_list(
            room_id,
            query.before_seq,
            query.after_seq,
            query.limit,
            &ctx,
        )
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/rooms/{room_id}/messages",
    params(
        ("room_id" = Uuid, Path),
    ),
    request_body = room::RoomMessageCreateRequest,
    responses(
        (status = 200, description = "Create room message", body = ApiResponse<room::RoomMessageResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn message_create(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<Uuid>,
    body: web::Json<room::RoomMessageCreateRequest>,
) -> Result<HttpResponse, ApiError> {
    let room_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
        .room_message_create(room_id, body.into_inner(), &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    patch,
    path = "/api/rooms/{room_id}/messages/{message_id}",
    params(
        ("room_id" = Uuid, Path),
        ("message_id" = Uuid, Path),
    ),
    request_body = room::RoomMessageUpdateRequest,
    responses(
        (status = 200, description = "Update room message", body = ApiResponse<room::RoomMessageResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn message_update(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(Uuid, Uuid)>,
    body: web::Json<room::RoomMessageUpdateRequest>,
) -> 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
        .room_message_update(message_id, body.into_inner(), &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/rooms/{room_id}/messages/{message_id}/revoke",
    params(
        ("room_id" = Uuid, Path),
        ("message_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "Revoke room message", body = ApiResponse<room::RoomMessageResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn message_revoke(
    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
        .room_message_revoke(message_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/rooms/{room_id}/messages/{message_id}",
    params(
        ("room_id" = Uuid, Path),
        ("message_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "Get room message", body = ApiResponse<room::RoomMessageResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn message_get(
    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
        .room_message_get(message_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}
