use uuid::Uuid;

use crate::{ChannelBus, ChannelError, ChannelResult};

use super::WsHandler;
use super::WsOutEvent;

impl WsHandler {
    pub(super) async fn user_summary(
        bus: &ChannelBus,
        username: String,
    ) -> ChannelResult<Option<WsOutEvent>> {
        let user = db::sqlx::query_as::<_, model::users::UserModel>(
            "SELECT id, username, display_name, avatar_url, website_url, \
             allow_use, can_search, last_sign_in_at, created_at, updated_at \
             FROM \"user\" WHERE username = $1",
        )
        .bind(&username)
        .fetch_one(bus.inner.db.reader())
        .await
        .map_err(|e| match e {
            db::sqlx::Error::RowNotFound => ChannelError::RoomNotFound,
            other => ChannelError::Database(other),
        })?;
        Ok(Some(WsOutEvent::Response {
            request_id: Uuid::nil(),
            data: serde_json::json!({
                "id": user.id,
                "username": user.username,
                "display_name": user.display_name,
                "avatar_url": user.avatar_url,
            }),
        }))
    }
}
