/*-------------------------------------------------------------------------
 * Copyright (c) Microsoft Corporation.  All rights reserved.
 *
 * documentdb_gateway_core/src/testing/pool.rs
 *
 * Shared connection-pool construction helpers for unit tests within the
 * gateway core crate.
 *
 *-------------------------------------------------------------------------
 */

use tokio::task::yield_now;

use crate::{
    configuration::{CertInputType, CertificateOptions, DocumentDBSetupConfiguration},
    postgres::{
        conn_mgmt::{ConnectionPool, PgPoolSettings},
        create_query_catalog,
    },
};

/// Returns a baseline `DocumentDBSetupConfiguration` suitable for connection
/// pool unit tests against a local `PostgreSQL` instance.
#[must_use]
pub fn test_setup_configuration() -> DocumentDBSetupConfiguration {
    let system_user = std::env::var("PostgresSystemUser").unwrap_or_else(|_| whoami::username());

    DocumentDBSetupConfiguration {
        node_host_name: "localhost".to_owned(),
        blocked_role_prefixes: Vec::new(),
        gateway_listen_port: Some(10260),
        allow_transaction_snapshot: Some(false),
        certificate_options: CertificateOptions {
            cert_type: CertInputType::PemAutoGenerated,
            ..Default::default()
        },
        postgres_system_user: system_user.clone(),
        postgres_data_user: system_user,
        ..Default::default()
    }
}

/// Builds a [`ConnectionPool`] for unit tests with the supplied user and
/// max connection count using the standard system pool settings.
///
/// The `async` signature lets tests `await` this helper directly without
/// nesting blocking calls inside async test bodies.
///
/// # Panics
///
/// Panics if the underlying pool fails to construct.
pub async fn test_connection_pool(
    setup_config: &DocumentDBSetupConfiguration,
    user: &str,
    max_connections: usize,
) -> ConnectionPool {
    yield_now().await;

    let query_catalog = create_query_catalog();
    ConnectionPool::new_with_user(
        setup_config,
        &query_catalog,
        user,
        None,
        "test-app",
        PgPoolSettings::system_pool_settings(max_connections),
    )
    .expect("Failed to create connection pool")
}
