//! User resolution — username <-> identity key lookups.

use quicproquo_proto::bytes::Bytes;
use quicproquo_proto::prost::Message;
use quicproquo_proto::{method_ids, qpq::v1};
use quicproquo_rpc::client::RpcClient;

use crate::error::SdkError;

/// Resolve a username to its identity key.
/// Returns `None` if the username is not registered.
pub async fn resolve_user(
    rpc: &RpcClient,
    username: &str,
) -> Result<Option<Vec<u8>>, SdkError> {
    let req = v1::ResolveUserRequest {
        username: username.to_string(),
    };
    let resp_bytes = rpc
        .call(method_ids::RESOLVE_USER, Bytes::from(req.encode_to_vec()))
        .await?;
    let resp = v1::ResolveUserResponse::decode(resp_bytes)
        .map_err(|e| SdkError::Other(anyhow::anyhow!("decode ResolveUserResponse: {e}")))?;
    if resp.identity_key.is_empty() {
        Ok(None)
    } else {
        Ok(Some(resp.identity_key))
    }
}

/// Reverse lookup: identity key to username.
/// Returns `None` if no username is associated with the key.
pub async fn resolve_identity(
    rpc: &RpcClient,
    identity_key: &[u8],
) -> Result<Option<String>, SdkError> {
    let req = v1::ResolveIdentityRequest {
        identity_key: identity_key.to_vec(),
    };
    let resp_bytes = rpc
        .call(method_ids::RESOLVE_IDENTITY, Bytes::from(req.encode_to_vec()))
        .await?;
    let resp = v1::ResolveIdentityResponse::decode(resp_bytes)
        .map_err(|e| SdkError::Other(anyhow::anyhow!("decode ResolveIdentityResponse: {e}")))?;
    if resp.username.is_empty() {
        Ok(None)
    } else {
        Ok(Some(resp.username))
    }
}
