use super::db::Database;
use super::db::DatabaseOperationError;
use super::db::{self};

#[tracing::instrument(skip_all, err)]
pub async fn run_migrations(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    if is_at_version(db, 2).await? {
        migrate_to_v3(db).await?;
    }
    Ok(())
}

#[tracing::instrument(skip_all, err)]
pub async fn migrate_to_v3(db: &Database) -> Result<(), Box<dyn std::error::Error>> {
    use redb::ReadableTableMetadata;
    tracing::warn!("MIGRATING TO VERSION 3");

    db.write(|txn| {
        // Opening the table creates the table
        let table = txn.open_table(db::current::TABLE_USER)?;
        assert!(table.is_empty()?);
        Ok(())
    })
    .await?;

    db.set_version(db::Version { version: db::v3::VERSION }).await?;

    Ok(())
}

async fn is_at_version(db: &Database, version: u64) -> Result<bool, DatabaseOperationError> {
    let v = db.get_version().await?;
    Ok(v == Some(db::Version { version }))
}
