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}/members",
    params(
        ("room_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "List room members", body = ApiResponse<Vec<room::RoomMemberResponse>>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn member_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_member_list(room_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/rooms/{room_id}/members",
    params(
        ("room_id" = Uuid, Path),
    ),
    request_body = room::RoomMemberAddRequest,
    responses(
        (status = 200, description = "Add room member", body = ApiResponse<room::RoomMemberResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn member_add(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<Uuid>,
    body: web::Json<room::RoomMemberAddRequest>,
) -> 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_member_add(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}/members/{user_id}/role",
    params(
        ("room_id" = Uuid, Path),
        ("user_id" = Uuid, Path),
    ),
    request_body = room::RoomMemberRoleUpdateRequest,
    responses(
        (status = 200, description = "Update member role", body = ApiResponse<room::RoomMemberResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn member_update_role(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(Uuid, Uuid)>,
    body: web::Json<room::RoomMemberRoleUpdateRequest>,
) -> Result<HttpResponse, ApiError> {
    let (room_id, user_id) = path.into_inner();
    let req = room::RoomMemberRoleUpdateRequest {
        user_id,
        role: body.into_inner().role,
    };
    let actor_id = session
        .user()
        .ok_or_else(|| ApiError::from(service::error::AppError::Unauthorized))?;
    let ctx = WsUserContext::new(actor_id);
    let resp = service
        .room
        .room_member_update_role(room_id, req, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/rooms/{room_id}/members/{user_id}",
    params(
        ("room_id" = Uuid, Path),
        ("user_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "Remove room member"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn member_remove(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(Uuid, Uuid)>,
) -> Result<HttpResponse, ApiError> {
    let (room_id, user_id) = path.into_inner();
    let actor_id = session
        .user()
        .ok_or_else(|| ApiError::from(service::error::AppError::Unauthorized))?;
    let ctx = WsUserContext::new(actor_id);
    service
        .room
        .room_member_remove(room_id, user_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(true).to_response())
}

#[utoipa::path(
    patch,
    path = "/api/rooms/{room_id}/members/me/read-seq",
    params(
        ("room_id" = Uuid, Path),
    ),
    request_body = room::RoomMemberReadSeqRequest,
    responses(
        (status = 200, description = "Set member read sequence", body = ApiResponse<room::RoomMemberResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn member_set_read_seq(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<Uuid>,
    body: web::Json<room::RoomMemberReadSeqRequest>,
) -> 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_member_set_read_seq(room_id, body.into_inner(), &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/rooms/{room_id}/members/me",
    params(
        ("room_id" = Uuid, Path),
    ),
    responses(
        (status = 200, description = "Leave room"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
    ),
    tag = "Room"
)]
pub async fn member_leave(
    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);
    service
        .room
        .room_member_leave(room_id, &ctx)
        .await
        .map_err(ApiError::from)?;
    Ok(ApiResponse::ok(true).to_response())
}
