#![cfg(not(target_arch = "wasm32"))]
//! Tests for vault keypair management and crypto operations
use vault::{Vault, KeyType, KeyMetadata};
use kvstore::native::NativeStore;

use log::debug;

#[tokio::test]
async fn test_keypair_management_and_crypto() {
    let _ = env_logger::builder().is_test(true).try_init();
    debug!("test_keypair_management_and_crypto started");
    // Use NativeStore for native tests
    #[cfg(not(target_arch = "wasm32"))]
    use tempfile::TempDir;
    let tmp_dir = TempDir::new().expect("create temp dir");
    let store = NativeStore::open(tmp_dir.path().to_str().unwrap()).expect("Failed to open native store");
    #[cfg(not(target_arch = "wasm32"))]
    let mut vault = Vault::new(store);
    #[cfg(target_arch = "wasm32")]
    compile_error!("This test is not intended for wasm32 targets");
    let keyspace = &format!("testspace_{}", chrono::Utc::now().timestamp_nanos_opt().unwrap());
    let password = b"supersecret";

    debug!("keyspace: {} password: {}", keyspace, hex::encode(password));
    debug!("before create_keyspace");
    vault.create_keyspace(keyspace, password, None).await.unwrap();

    debug!("after create_keyspace: keyspace={} password={}", keyspace, hex::encode(password));
    debug!("before add Ed25519 keypair");
    let key_id = vault.add_keypair(keyspace, password, Some(KeyType::Ed25519), Some(KeyMetadata { name: Some("edkey".into()), created_at: None, tags: None })).await;
    match &key_id {
        Ok(_) => debug!("after add Ed25519 keypair (Ok)"),
        Err(e) => debug!("after add Ed25519 keypair (Err): {:?}", e),
    }
    let key_id = key_id.unwrap();
    debug!("before add secp256k1 keypair");
    let secp_id = vault.add_keypair(keyspace, password, None, Some(KeyMetadata { name: Some("secpkey".into()), created_at: None, tags: None })).await.unwrap();

    debug!("before list_keypairs");
    let keys = vault.list_keypairs(keyspace, password).await.unwrap();
    assert_eq!(keys.len(), 2);

    debug!("before export Ed25519 keypair");
    let (priv_bytes, pub_bytes) = vault.export_keypair(keyspace, password, &key_id).await.unwrap();
    assert!(!priv_bytes.is_empty() && !pub_bytes.is_empty());

    debug!("before sign Ed25519");
    let msg = b"hello world";
    let sig = vault.sign(keyspace, password, &key_id, msg).await.unwrap();
    debug!("before verify Ed25519");
    let ok = vault.verify(keyspace, password, &key_id, msg, &sig).await.unwrap();
    assert!(ok);

    debug!("before sign secp256k1");
    let sig2 = vault.sign(keyspace, password, &secp_id, msg).await.unwrap();
    debug!("before verify secp256k1");
    let ok2 = vault.verify(keyspace, password, &secp_id, msg, &sig2).await.unwrap();
    assert!(ok2);

    // Encrypt and decrypt
    let ciphertext = vault.encrypt(keyspace, password, msg).await.unwrap();
    let plaintext = vault.decrypt(keyspace, password, &ciphertext).await.unwrap();
    assert_eq!(plaintext, msg);

    // Remove a keypair
    vault.remove_keypair(keyspace, password, &key_id).await.unwrap();
    let keys = vault.list_keypairs(keyspace, password).await.unwrap();
    assert_eq!(keys.len(), 1);
}
