//! Node state management: lifecycle, membership, clock operations.

use super::ChaosNode;
use std::sync::Arc;
use stemedb_cluster::membership::{NodeId, NodeInfo, NodeState};
use stemedb_core::types::HlcTimestamp;
use tracing::debug;

impl ChaosNode {
    /// Simulates node failure (stops accepting operations).
    pub fn kill(&mut self) {
        debug!(node = self.index, "Node killed");
        self.alive = false;
    }

    /// Simulates node recovery.
    pub fn revive(&mut self) {
        debug!(node = self.index, "Node revived");
        self.alive = true;
    }

    /// Returns whether this node is alive.
    pub fn is_alive(&self) -> bool {
        self.alive
    }

    /// Gets the membership manager for this node.
    pub fn membership(&self) -> &Arc<stemedb_cluster::membership::SwimMembership> {
        &self.membership
    }

    /// Marks a peer node as suspected (for SWIM testing).
    pub fn suspect_peer(&self, peer_id: NodeId) {
        self.membership.suspect_node(peer_id);
    }

    /// Marks a peer node as alive (for SWIM testing).
    pub fn alive_peer(&self, peer_id: NodeId, info: NodeInfo) {
        self.membership.alive_node(peer_id, info);
    }

    /// Gets the state of a peer from this node's perspective.
    pub fn get_peer_state(&self, peer_id: NodeId) -> Option<NodeState> {
        self.membership
            .all_members()
            .into_iter()
            .find(|(info, _)| info.id == peer_id)
            .map(|(_, state)| state)
    }

    /// Returns the current HLC timestamp for this node (with skew).
    pub fn current_hlc(&self) -> HlcTimestamp {
        self.hlc.new_timestamp()
    }

    /// Returns the clock skew offset for this node in milliseconds.
    pub fn clock_offset_ms(&self) -> i64 {
        self.clock_controller.get_offset(self.index)
    }
}
