//! P2P endpoint domain logic — publish, resolve, health.

use std::sync::Arc;

use crate::storage::Store;

use super::types::*;

/// Domain service for P2P endpoint management and health checks.
pub struct P2pService {
    pub store: Arc<dyn Store>,
}

impl P2pService {
    pub fn publish_endpoint(
        &self,
        req: PublishEndpointReq,
        _auth: &CallerAuth,
    ) -> Result<(), DomainError> {
        if req.identity_key.len() != 32 {
            return Err(DomainError::InvalidIdentityKey(req.identity_key.len()));
        }

        self.store
            .publish_endpoint(&req.identity_key, req.node_addr)?;
        Ok(())
    }

    pub fn resolve_endpoint(
        &self,
        req: ResolveEndpointReq,
        _auth: &CallerAuth,
    ) -> Result<ResolveEndpointResp, DomainError> {
        if req.identity_key.len() != 32 {
            return Err(DomainError::InvalidIdentityKey(req.identity_key.len()));
        }

        let node_addr = self
            .store
            .resolve_endpoint(&req.identity_key)?
            .unwrap_or_default();
        Ok(ResolveEndpointResp { node_addr })
    }

    pub fn health() -> HealthResp {
        HealthResp {
            status: "ok".into(),
        }
    }
}
