use serde::{Deserialize, Serialize};
use sqlx::{migrate, PgPool};

pub mod player_data;
pub mod sdk_data;

#[derive(Serialize, Deserialize)]
pub struct DatabaseCredentials {
    pub username: String,
    pub password: String,
    pub host: String,
    pub name: String,
}

impl ToString for DatabaseCredentials {
    fn to_string(&self) -> String {
        format!(
            "postgres://{}:{}@{}/{}",
            &self.username, &self.password, &self.host, &self.name
        )
    }
}

impl Default for DatabaseCredentials {
    fn default() -> Self {
        Self {
            username: String::from("root"),
            password: String::from("root"),
            host: String::from("localhost:5432"),
            name: String::from("nap"),
        }
    }
}

pub async fn init(credentials: &DatabaseCredentials) -> Result<PgPool, sqlx::Error> {
    let pool = PgPool::connect(&credentials.to_string()).await?;
    migrate!("./migrations").run(&pool).await?;

    Ok(pool)
}
