// Copyright © 2023 Kim Altintop <kim@eagain.io>
// SPDX-License-Identifier: GPL-2.0-only

use automerge::transaction::Transactable;
use itertools::Itertools;

use crate::index;

#[test]
fn test_store_load() -> anyhow::Result<()> {
    // The automerge README example
    let mut doc = automerge::AutoCommit::new();
    let contacts = doc.put_object(automerge::ROOT, "contacts", automerge::ObjType::List)?;
    let alice = doc.insert_object(&contacts, 0, automerge::ObjType::Map)?;
    doc.put(&alice, "name", "Alice")?;
    doc.put(&alice, "email", "alice@example.com")?;
    let bob = doc.insert_object(&contacts, 1, automerge::ObjType::Map)?;
    doc.put(&bob, "name", "Bob")?;
    doc.put(&bob, "email", "bob@example.com")?;
    doc.commit();

    let g = index::Sanakirja::new(None)?;
    let mut txn = g.mut_txn_begin()?;
    let mut idx = txn.create_doc("test")?;

    let changes = doc
        .get_changes(&[])
        .into_iter()
        .map(|change| change.hash())
        .collect::<Vec<_>>();
    idx.extend_with(&mut txn, changes.iter().copied())?;
    let stored = idx
        .changes(&txn)
        .map_ok(|(_, hash)| hash)
        .collect::<Result<Vec<_>, _>>()?;

    assert_eq!(changes, stored);

    Ok(())
}