#![forbid(unsafe_code)]

use rocket::{fairing::AdHoc, Build, Rocket};
use sqlx::{postgres::PgConnectOptions, PgPool};
use std::env;

async fn init(rocket: Rocket<Build>) -> rocket::fairing::Result {
    let pool = PgPool::connect_with({
        PgConnectOptions::new()
            .host(
                env::var("PGHOST")
                    .unwrap_or_else(|_| "localhost".into())
                    .as_str(),
            )
            .port(
                env::var("PGPORT")
                    .unwrap_or_else(|_| "5432".into())
                    .parse::<u16>()
                    .unwrap_or_default(),
            )
            .username(
                env::var("PGUSER")
                    .unwrap_or_else(|_| "postgres".into())
                    .as_str(),
            )
            .password(
                env::var("PGPASS")
                    .unwrap_or_else(|_| "postgres".into())
                    .as_str(),
            )
            .database(
                env::var("PGDBNAME")
                    .unwrap_or_else(|_| "postgres".into())
                    .as_str(),
            )
    })
    .await
    .expect("Failed to connect to PostgreSQL database.");

    Ok(rocket.manage(pool))
}

pub fn postgres_fairing() -> AdHoc {
    AdHoc::on_ignite("SQLx Connection", |rocket| async {
        rocket.attach(AdHoc::try_on_ignite("PostgreSQL Pool", init))
    })
}
