// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use rialo_cdk::{
        config::ConfigManager,
        keyring::{InMemoryKeyringProvider, KeyringProvider},
    };
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_keyring_with_config_manager() {
        // Setup
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("integration_test.toml");

        let config_manager = Arc::new(ConfigManager::new(&config_path).unwrap());
        let keyring_provider = Arc::new(InMemoryKeyringProvider::new());

        // Create keyring
        let keyring = keyring_provider
            .create("test_keyring", "password123")
            .await
            .unwrap();

        // Update config to use this keyring using ConfigManager
        config_manager
            .set("default_wallet", "test_keyring")
            .unwrap();

        // Verify config was updated correctly (should work with interior mutability)
        let loaded_config = config_manager.load().unwrap();
        assert_eq!(
            loaded_config.cdk.as_ref().unwrap().default_wallet,
            Some("test_keyring".to_string())
        );

        // Verify we can also get individual values
        let default_keyring: String = config_manager.get("default_wallet").unwrap();
        assert_eq!(default_keyring, "test_keyring");

        // Verify keyring can be loaded with this config
        let loaded_keyring = keyring_provider
            .load("test_keyring", "password123")
            .await
            .unwrap();
        assert_eq!(keyring.pubkey_string(), loaded_keyring.pubkey_string());
    }

    #[tokio::test]
    async fn test_config_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("persistence_test.toml");

        // Create first manager and set some values
        {
            let manager = ConfigManager::new(&config_path).unwrap();
            manager.set("default_wallet", "persistent_wallet").unwrap();
            manager.set("verbose_mode", true).unwrap();
            manager.set("network", "testnet").unwrap();
        }

        // Create second manager and verify values persist
        {
            let manager = ConfigManager::new(&config_path).unwrap();
            let config = manager.load().unwrap();

            assert_eq!(
                config.cdk.as_ref().unwrap().default_wallet,
                Some("persistent_wallet".to_string())
            );
            assert!(config.cdk.as_ref().unwrap().verbose_mode);
            assert_eq!(config.cdk.as_ref().unwrap().network.to_string(), "testnet");
        }
    }
}
