use rocksdb::WriteBatch;

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.net/notification.xml".to_string()),
            object_type: Some(object_type.to_string()),
            state: RepositoryViewState::Present,
        })
        .expect("put repository view");
}

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

    put_current_object(&store, "rsync://example.net/repo/a/1.cer", b"1", "cer");
    put_current_object(&store, "rsync://example.net/repo/a/2.cer", b"2", "cer");
    put_current_object(&store, "rsync://example.net/repo/b/1.cer", b"3", "cer");

    let prefix = "rsync://example.net/repo/a/";
    let items = store
        .list_repository_view_entries_with_prefix(prefix)
        .expect("iter")
        .into_iter()
        .map(|entry| entry.rsync_uri)
        .collect::<Vec<_>>();

    assert_eq!(items.len(), 2);
    for k in &items {
        assert!(k.starts_with("rsync://example.net/repo/a/"));
    }
}

#[test]
fn storage_write_batch_accepts_empty_batch() {
    let temp = tempfile::tempdir().expect("tempdir");
    let store = RocksStore::open(temp.path()).expect("open rocksdb");
    store
        .write_batch(WriteBatch::default())
        .expect("write batch");
}
