//! Shared helpers for remote peer identity.

use std::{net::SocketAddr, sync::Arc};

use tokio::sync::RwLock;

use crate::peer_db::{PeerGameDB, PeerId};

pub async fn ensure_peer_id_for_addr(
    peer_game_db: &Arc<RwLock<PeerGameDB>>,
    peer_addr: SocketAddr,
) -> PeerId {
    let mut db = peer_game_db.write().await;
    if let Some(peer_id) = db.peer_id_for_addr(&peer_addr).cloned() {
        return peer_id;
    }

    let addr_id = format!("addr-{peer_addr}");
    db.upsert_peer(addr_id.clone(), peer_addr);
    addr_id
}
