/// Strict compatibility serving limit used on request path.
pub const MAX_KEYSPACE_GROUP_COUNT_IN_USE: u32 = 4096;
/// Global ID-space capacity used in key formatting.
pub const MAX_KEYSPACE_GROUP_COUNT: u32 = 100_000;
/// Default keyspace group id.
pub const DEFAULT_KEYSPACE_GROUP_ID: u32 = 0;

/// Returns timestamp key path for a given group.
#[must_use]
pub fn timestamp_path(cluster_id: u64, group_id: u32) -> String {
    if group_id == DEFAULT_KEYSPACE_GROUP_ID {
        format!("/pd/{cluster_id}/timestamp")
    } else {
        format!("/ms/{cluster_id}/tso/{group_id:05}/gta/timestamp")
    }
}

/// Returns primary-election key path for a given group.
#[must_use]
pub fn election_path(cluster_id: u64, group_id: u32) -> String {
    if group_id == DEFAULT_KEYSPACE_GROUP_ID {
        format!("/ms/{cluster_id}/tso/00000/primary")
    } else {
        format!("/ms/{cluster_id}/tso/keyspace_groups/election/{group_id:05}/primary")
    }
}

/// Returns expected-primary key path for a given group.
#[must_use]
pub fn expected_primary_path(cluster_id: u64, group_id: u32) -> String {
    if group_id == DEFAULT_KEYSPACE_GROUP_ID {
        format!("/ms/{cluster_id}/tso/00000/primary/expected_primary")
    } else {
        format!(
            "/ms/{cluster_id}/tso/keyspace_groups/election/{group_id:05}/primary/expected_primary"
        )
    }
}

/// Returns keyspace-group membership metadata path.
#[must_use]
pub fn membership_path(cluster_id: u64, group_id: u32) -> String {
    format!("/pd/{cluster_id}/tso/keyspace_groups/membership/{group_id:05}")
}

#[cfg(test)]
mod tests {
    use super::{election_path, expected_primary_path, membership_path, timestamp_path};

    #[test]
    fn key_layout_matches_contract() {
        assert_eq!(timestamp_path(42, 0), "/pd/42/timestamp");
        assert_eq!(timestamp_path(42, 7), "/ms/42/tso/00007/gta/timestamp");
        assert_eq!(
            election_path(42, 7),
            "/ms/42/tso/keyspace_groups/election/00007/primary"
        );
        assert_eq!(
            expected_primary_path(42, 0),
            "/ms/42/tso/00000/primary/expected_primary"
        );
        assert_eq!(
            membership_path(42, 7),
            "/pd/42/tso/keyspace_groups/membership/00007"
        );
    }
}
