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 ThreadMessagesQuery {
    pub before_seq: Option<i64>,
    pub after_seq: Option<i64>,
    pub limit: Option<u64>,
}

#[utoipa::path(
    get,
    path = "/api/rooms/{room_id}/threads",
    params(
        ("room_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "List room threads", body = ApiResponse<Vec<room::RoomThreadResponse>>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn thread_list(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<Uuid>,
) -> 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_thread_list(room_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

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

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