use sqlx::postgres::{PgPoolOptions};
use sqlx::{Postgres, Pool};
use tokio::sync::OnceCell;
use log::error;

/// A connection pool to the Postgres database
static PG_POOL: OnceCell<Pool<Postgres>> = OnceCell::const_new();

/// Get a reference to the Postgres connection pool
pub(crate) async fn get_pool() -> Result<&'static Pool<Postgres>, sqlx::Error> {

    PG_POOL
        .get_or_try_init(|| async {
            let connection_uri = format!("postgres://{PG__USER}:{PG__PASSWORD}@{PG__HOST}:{PG__PORT}/{PG__DBNAME}",
                PG__USER = std::env::var("PG__USER").unwrap(),
                PG__PASSWORD = std::env::var("PG__PASSWORD").unwrap(),
                PG__HOST = std::env::var("PG__HOST").unwrap(),
                PG__PORT = std::env::var("PG__PORT").unwrap(),
                PG__DBNAME = std::env::var("PG__DBNAME").unwrap()
            );

            PgPoolOptions::new()
                .max_connections(5)
                .connect(&connection_uri)
                .await
                .map_err(|e| {
                    error!("Failed to connect to Postgres: {:?}", e);
                    e
                })
        }).await
}
