use paas_client::pseudonym_service::PseudonymService;
use std::fmt;
use std::fmt::Debug;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::{Mutex, MutexGuard};

/// A pool of PseudonymService instances to enable concurrent operations
/// without blocking on a single mutex.
///
/// Uses round-robin distribution to balance load across instances.
/// Each instance maintains its own independent session with the transcryptors.
#[derive(Clone)]
pub struct PseudonymServicePool {
    services: Arc<Vec<Mutex<PseudonymService>>>,
    counter: Arc<AtomicUsize>,
}

impl PseudonymServicePool {
    /// Create a new pool with the specified services
    pub fn new(services: Vec<PseudonymService>) -> Self {
        Self {
            services: Arc::new(services.into_iter().map(Mutex::new).collect()),
            counter: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Acquire a PseudonymService from the pool using round-robin distribution
    pub async fn acquire(&self) -> MutexGuard<'_, PseudonymService> {
        let idx = self.counter.fetch_add(1, Ordering::Relaxed) % self.services.len();
        self.services[idx].lock().await
    }
}

impl Debug for PseudonymServicePool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PseudonymServicePool")
            .field("size", &self.services.len())
            .field(
                "current_counter",
                &self.counter.load(std::sync::atomic::Ordering::Relaxed),
            )
            .finish()
    }
}
