//! Defines basic functions for creating IDs for transactions. These should be called once per transaction in the transaction
//! interface and then passed to all actors in a message.

/// Creates a transaction ID based on the connection index, transaction index, and the current timestamp.
///
/// # Arguments
/// * `connection_index`: The index of the connection in the allocator
/// * `transaction_index`: The index of the transaction in the connection
///
/// # Returns
/// A string representing the transaction ID
pub fn create_id(connection_index: usize, transaction_index: usize) -> String {
	let timestamp = chrono::Utc::now().timestamp().to_string();
	format!("{}-{}-{}", connection_index, transaction_index, timestamp)
}

/// Gets the connection index from the transaction ID.
///
/// # Arguments
/// * `id`: The transaction ID
///
/// # Returns
/// The connection index
pub fn get_connection_index(id: &str) -> usize {
	let parts: Vec<&str> = id.split("-").collect();
	parts[0].parse::<usize>().unwrap()
}

/// Gets the transaction index from the transaction ID.
///
/// # Arguments
/// * `id`: The transaction ID
///
/// # Returns
/// The transaction index
pub fn get_transaction_index(id: &str) -> usize {
	let parts: Vec<&str> = id.split("-").collect();
	parts[1].parse::<usize>().unwrap()
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_create_id() {
		let id = create_id(1, 1);
		assert_eq!(id.len(), 14);
		assert!(id.contains("1-1-"));
	}

	#[test]
	fn test_get_connection_index() {
		let id = create_id(1, 2);
		let index = get_connection_index(&id);
		assert_eq!(index, 1);
	}

	#[test]
	fn test_get_transaction_index() {
		let id = create_id(1, 2);
		let index = get_transaction_index(&id);
		assert_eq!(index, 2);
	}
}
