//! Integration tests for vault secrets management
//!
//! These tests verify the vault secrets integration works correctly
//! by testing the core components in isolation.
//!
//! NOTE: These tests are disabled due to API mismatches (KmsServiceClient::new
//! signature changed) Re-enable after updating the tests to match the current
//! API

// Disabled: API mismatches
#![allow(unexpected_cfgs)]
#![cfg(feature = "vault_integration_tests")]
#![allow(unused_imports)]

use std::sync::Arc;

use base64::{engine::general_purpose, Engine as _};
use control_center::kms::audit::AuditLogger;
use control_center::kms::kms_service_client::KmsServiceClient;
use control_center::services::secrets::SecretsService;
use control_center::storage::surrealdb_storage::SurrealDbStorage;

#[tokio::test]
async fn test_kms_client_encrypt_decrypt() {
    // Test KMS Service client can encrypt and decrypt
    let kms_client = KmsServiceClient::new("http://localhost:8081".to_string(), 3);

    let plaintext = b"test secret value";
    let context = Some("test-context");

    // Encrypt
    let ciphertext = kms_client
        .encrypt(plaintext, context)
        .await
        .expect("Failed to encrypt");

    assert!(!ciphertext.is_empty(), "Ciphertext should not be empty");
    assert_ne!(
        ciphertext, plaintext,
        "Ciphertext should differ from plaintext"
    );

    // Decrypt
    let decrypted = kms_client
        .decrypt(&ciphertext, context)
        .await
        .expect("Failed to decrypt");

    assert_eq!(
        decrypted, plaintext,
        "Decrypted value should match original"
    );
}

#[tokio::test]
async fn test_kms_client_health_check() {
    let kms_client = KmsServiceClient::new("http://localhost:8081".to_string(), 3);

    let is_healthy = kms_client
        .health_check()
        .await
        .expect("Health check failed");

    assert!(is_healthy, "KMS Service should be healthy");
}

#[tokio::test]
async fn test_kms_client_generate_data_key() {
    let kms_client = KmsServiceClient::new("http://localhost:8081".to_string(), 3);

    let key_spec = "AES_256"; // Key specification

    let data_key = kms_client
        .generate_data_key(key_spec)
        .await
        .expect("Failed to generate data key");

    assert!(
        !data_key.plaintext.is_empty(),
        "Plaintext key should not be empty"
    );
    assert!(
        !data_key.ciphertext.is_empty(),
        "Encrypted key should not be empty"
    );
    assert!(!data_key.key_id.is_empty(), "Key ID should not be empty");

    // Verify plaintext is base64 encoded
    let plaintext_bytes = general_purpose::STANDARD
        .decode(&data_key.plaintext)
        .expect("Plaintext should be valid base64");
    assert_eq!(
        plaintext_bytes.len(),
        32,
        "Decoded plaintext should be 32 bytes for AES-256"
    );

    // Verify we can decrypt the encrypted key and it matches the plaintext
    let decrypted_key = kms_client
        .decrypt(data_key.ciphertext.as_bytes(), None)
        .await
        .expect("Failed to decrypt data key");

    assert_eq!(
        decrypted_key, plaintext_bytes,
        "Decrypted key should match plaintext key"
    );
}

#[tokio::test]
#[ignore] // Requires SurrealDB running
async fn test_secret_lifecycle_with_storage() {
    // This test would verify the full secret lifecycle:
    // 1. Create secret (encrypt + store metadata)
    // 2. Retrieve secret (fetch metadata + decrypt)
    // 3. Update secret (new version)
    // 4. List secrets
    // 5. Get history
    // 6. Delete secret

    // Skipped for now due to SurrealDB dependency and control-center
    // compilation issues Once control-center builds successfully, this can
    // be enabled
}

#[test]
fn test_vault_secret_serialization() {
    use control_center::services::secrets::VaultSecret;
    use serde_json;

    let secret = VaultSecret {
        id: "secret:test-123".to_string(),
        path: "database/prod/password".to_string(),
        encrypted_value: "base64encodedciphertext".to_string(),
        version: 1,
        created_at: "2025-10-08T00:00:00Z".to_string(),
        updated_at: "2025-10-08T00:00:00Z".to_string(),
        created_by: "user:alice".to_string(),
        updated_by: "user:alice".to_string(),
        deleted: false,
        encryption_context: Some("production".to_string()),
        metadata: Some(serde_json::json!({"environment": "prod"})),
    };

    // Test serialization
    let json = serde_json::to_string(&secret).expect("Failed to serialize");
    assert!(json.contains("database/prod/password"));
    assert!(json.contains("production"));

    // Test deserialization
    let deserialized: VaultSecret = serde_json::from_str(&json).expect("Failed to deserialize");
    assert_eq!(deserialized.id, secret.id);
    assert_eq!(deserialized.path, secret.path);
    assert_eq!(deserialized.version, secret.version);
}
