#![cfg(target_arch = "wasm32")]
//! WASM/browser tests for kvstore using wasm-bindgen-test

use kvstore::{WasmStore, KVStore};
use wasm_bindgen_test::*;

wasm_bindgen_test_configure!(run_in_browser);

#[wasm_bindgen_test]
async fn test_set_and_get() {
    let store = WasmStore::open("vault").await.expect("open");
    store.set("foo", b"bar").await.expect("set");
    let val = store.get("foo").await.expect("get");
    assert_eq!(val, Some(b"bar".to_vec()));
}

#[wasm_bindgen_test]
async fn test_delete_and_exists() {
    let store = WasmStore::open("vault").await.expect("open");
    store.set("foo", b"bar").await.expect("set");
    assert_eq!(store.contains_key("foo").await.unwrap(), true);
    assert_eq!(store.contains_key("bar").await.unwrap(), false);
    store.remove("foo").await.unwrap();
    assert_eq!(store.get("foo").await.unwrap(), None);
}

#[wasm_bindgen_test]
async fn test_keys() {
    let store = WasmStore::open("vault").await.expect("open");
    store.set("foo", b"bar").await.expect("set");
    store.set("baz", b"qux").await.expect("set");
    let keys = store.keys().await.unwrap();
    assert_eq!(keys.len(), 2);
    assert!(keys.contains(&"foo".to_string()));
    assert!(keys.contains(&"baz".to_string()));
}

#[wasm_bindgen_test]
async fn test_wasm_store_persistence() {
    // Use a unique store name to avoid collisions
    let store_name = "persist_test_store";
    // First open, set value
    {
        let store = WasmStore::open(store_name).await.expect("open");
        store.set("persist", b"value").await.expect("set");
    }
    // Reopen and check value
    {
        let store = WasmStore::open(store_name).await.expect("open");
        let val = store.get("persist").await.expect("get");
        assert_eq!(val, Some(b"value".to_vec()));
    }
}

#[wasm_bindgen_test]
async fn test_clear() {
    let store = WasmStore::open("vault").await.expect("open");
    store.set("foo", b"bar").await.expect("set");
    store.set("baz", b"qux").await.expect("set");
    store.clear().await.unwrap();
    let keys = store.keys().await.unwrap();
    assert_eq!(keys.len(), 0);
}
