use aws_local_core::db::DbPool;

pub fn connect(data_dir: &str) -> rusqlite::Result<DbPool> {
    aws_local_core::db::connect(data_dir, "rds.db")
}

pub use aws_local_core::db::connect_in_memory;

pub fn run_migrations(db: &DbPool) -> rusqlite::Result<()> {
    let conn = db.lock().unwrap();
    conn.execute_batch(
        "CREATE TABLE IF NOT EXISTS db_instances (
            db_instance_identifier TEXT PRIMARY KEY,
            db_instance_class      TEXT NOT NULL DEFAULT 'db.t3.micro',
            engine                 TEXT NOT NULL DEFAULT 'postgres',
            engine_version         TEXT NOT NULL DEFAULT '16',
            master_username        TEXT NOT NULL,
            password_hash          TEXT NOT NULL,
            db_name                TEXT,
            allocated_storage      INTEGER NOT NULL DEFAULT 20,
            status                 TEXT NOT NULL DEFAULT 'available',
            endpoint_address       TEXT NOT NULL,
            endpoint_port          INTEGER NOT NULL,
            created_at             TEXT NOT NULL,
            db_cluster_identifier  TEXT
        );

        CREATE TABLE IF NOT EXISTS db_clusters (
            db_cluster_identifier  TEXT PRIMARY KEY,
            engine                 TEXT NOT NULL DEFAULT 'aurora-postgresql',
            engine_version         TEXT NOT NULL DEFAULT '16',
            master_username        TEXT NOT NULL,
            password_hash          TEXT NOT NULL,
            database_name          TEXT,
            status                 TEXT NOT NULL DEFAULT 'available',
            endpoint_address       TEXT NOT NULL,
            endpoint_port          INTEGER NOT NULL,
            created_at             TEXT NOT NULL
        );"
    )?;
    // Add db_cluster_identifier column to existing databases
    let _ = conn.execute_batch(
        "ALTER TABLE db_instances ADD COLUMN db_cluster_identifier TEXT;"
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn migrations_run_and_are_idempotent() {
        let db = connect_in_memory().unwrap();
        run_migrations(&db).unwrap();
        run_migrations(&db).unwrap();
        let conn = db.lock().unwrap();
        let count: i64 = conn.query_row(
            "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name IN ('db_instances','db_clusters')",
            [], |r| r.get(0),
        ).unwrap();
        assert_eq!(count, 2);
    }
}
