Open source Nest implementation
use std::env;

use rocket::{
    fairing::{self, AdHoc},
    Build, Rocket,
};

pub type Database = sqlx::PgPool;

async fn init_db(rocket: Rocket<Build>) -> fairing::Result {
    let database_url = match env::var("DATABASE_URL") {
        Ok(val) => val,
        Err(e) => {
            error!("Failed to read DATABASE_URL environment variable: {}", e);
            return Err(rocket);
        }
    };

    let pool = sqlx::PgPool::connect(&database_url)
        .await
        .expect("Failed to connect to the database");

    if let Err(e) = sqlx::migrate!("./migrations").run(&pool).await {
        error!("Failed to migrate PG database: {}", e);
        return Err(rocket);
    }

    Ok(rocket.manage(pool))
}

pub fn stage() -> AdHoc {
    AdHoc::on_ignite("SQL Stage - PostgreSQL", |rocket| async {
        rocket.attach(AdHoc::try_on_ignite("Postgres Database", init_db))
    })
}