use anyhow::Result;
use sea_orm::{Database, DatabaseConnection};

pub async fn connect(db_path: &str) -> Result<DatabaseConnection> {
    let url = if db_path == ":memory:" || db_path == "sqlite::memory:" {
        "sqlite::memory:".to_string()
    } else {
        format!("sqlite://{}?mode=rwc", db_path)
    };
    let db = Database::connect(&url).await?;
    Ok(db)
}

pub async fn connect_and_migrate(db_path: &str) -> Result<DatabaseConnection> {
    let db = connect(db_path).await?;
    run_migrations(&db).await?;
    Ok(db)
}

pub async fn run_migrations(db: &DatabaseConnection) -> Result<()> {
    use crate::migration::MigratorTrait;
    crate::migration::Migrator::up(db, None).await?;
    Ok(())
}
