use aws_local_core::db::DbPool;

pub fn connect(data_dir: &str) -> rusqlite::Result<DbPool> {
    aws_local_core::db::connect(data_dir, "resources.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 resources (
            arn         TEXT PRIMARY KEY,
            service     TEXT NOT NULL,
            type        TEXT NOT NULL,
            identifier  TEXT NOT NULL,
            region      TEXT NOT NULL DEFAULT 'us-east-1',
            account_id  TEXT NOT NULL DEFAULT '000000000000',
            properties  TEXT NOT NULL DEFAULT '{}',
            status      TEXT NOT NULL DEFAULT 'available',
            created_at  TEXT NOT NULL,
            updated_at  TEXT NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_resources_service_type ON resources(service, type);
        CREATE INDEX IF NOT EXISTS idx_resources_lookup ON resources(service, type, identifier);",
    )?;
    Ok(())
}

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

    #[test]
    fn migrations_idempotent() {
        let db = connect_in_memory().unwrap();
        run_migrations(&db).unwrap();
        run_migrations(&db).unwrap();
    }
}
