use rpki::storage::{RawByHashEntry, RepositoryViewEntry, RepositoryViewState, RocksStore};
use sha2::Digest;

fn put_current_object(store: &RocksStore, rsync_uri: &str, bytes: &[u8], object_type: &str) {
    let sha256_hex = hex::encode(sha2::Sha256::digest(bytes));
    let mut raw = RawByHashEntry::from_bytes(sha256_hex.clone(), bytes.to_vec());
    raw.origin_uris.push(rsync_uri.to_string());
    raw.object_type = Some(object_type.to_string());
    raw.encoding = Some("der".to_string());
    store.put_raw_by_hash_entry(&raw).expect("put raw_by_hash");
    store
        .put_repository_view_entry(&RepositoryViewEntry {
            rsync_uri: rsync_uri.to_string(),
            current_hash: Some(sha256_hex),
            repository_source: Some("https://example.test/notification.xml".to_string()),
            object_type: Some(object_type.to_string()),
            state: RepositoryViewState::Present,
        })
        .expect("put repository view");
}

#[test]
fn storage_iter_all_lists_repository_view_entries() {
    let temp = tempfile::tempdir().expect("tempdir");
    let store = RocksStore::open(temp.path()).expect("open rocksdb");

    put_current_object(&store, "rsync://example.test/repo/a.cer", b"a", "cer");
    put_current_object(&store, "rsync://example.test/repo/b.roa", b"b", "roa");

    let raw_keys = store
        .list_repository_view_entries_with_prefix("rsync://")
        .expect("list repository_view")
        .into_iter()
        .map(|entry| entry.rsync_uri)
        .collect::<Vec<_>>();
    assert_eq!(raw_keys.len(), 2);
    assert!(raw_keys.contains(&"rsync://example.test/repo/a.cer".to_string()));
    assert!(raw_keys.contains(&"rsync://example.test/repo/b.roa".to_string()));
}
