#!/usr/bin/env nu

# KMS Plugin Integration Tests
# Tests encryption, decryption, backend detection, and performance

use std assert

# Test plugin availability
export def test_kms_plugin_available [] {
    print "  Testing KMS plugin availability..."

    # Check if kms plugin is registered
    let available = (which kms | length) > 0

    # Should not error
    assert ($available == true or $available == false)

    if $available {
        print "    ✅ KMS plugin is available"
    } else {
        print "    ⚠️  KMS plugin not available (will use SOPS fallback)"
    }
}

# Test encryption with fallback
export def test_encryption [] {
    print "  Testing encryption..."

    use kms.nu *

    # Test data
    let test_data = "Hello, KMS test!"

    # Try encrypt with fallback
    let result = (do {
        plugin-kms-encrypt $test_data "age"
    } | complete)

    # Should either succeed or fail gracefully
    if $result.exit_code == 0 {
        print "    ✅ Encryption succeeded"
        return true
    } else {
        print "    ⚠️  Encryption failed (expected if no KMS backend available)"
        return false
    }
}

# Test decryption with fallback
export def test_decryption [] {
    print "  Testing decryption..."

    use kms.nu *

    # First encrypt some data
    let test_data = "Hello, KMS test!"
    let encrypt_result = (do {
        plugin-kms-encrypt $test_data "age"
    } | complete)

    if $encrypt_result.exit_code != 0 {
        print "    ⚠️  Skipping decryption test (encryption not available)"
        return
    }

    # Try to decrypt
    let encrypted = $encrypt_result.stdout
    let decrypt_result = (do {
        plugin-kms-decrypt $encrypted "age"
    } | complete)

    if $decrypt_result.exit_code == 0 {
        # Verify round-trip
        assert ($decrypt_result.stdout == $test_data)
        print "    ✅ Decryption succeeded (round-trip verified)"
    } else {
        print "    ⚠️  Decryption failed"
    }
}

# Test encryption round-trip
export def test_encrypt_decrypt_roundtrip [] {
    print "  Testing encryption round-trip..."

    use kms.nu *

    let test_data = "Secret message for round-trip test"

    # Try full round-trip
    let result = (do {
        let encrypted = (plugin-kms-encrypt $test_data "age" | complete)
        if $encrypted.exit_code != 0 {
            return {success: false, reason: "encryption_failed"}
        }

        let decrypted = (plugin-kms-decrypt $encrypted.stdout "age" | complete)
        if $decrypted.exit_code != 0 {
            return {success: false, reason: "decryption_failed"}
        }

        if $decrypted.stdout != $test_data {
            return {success: false, reason: "data_mismatch"}
        }

        {success: true}
    } | complete)

    if $result.exit_code == 0 {
        let parsed = ($result.stdout | from json)
        if $parsed.success {
            print "    ✅ Round-trip test passed"
        } else {
            print $"    ⚠️  Round-trip failed: ($parsed.reason)"
        }
    } else {
        print "    ⚠️  Round-trip test failed"
    }
}

# Test backend detection
export def test_backend_detection [] {
    print "  Testing backend detection..."

    use kms.nu *

    let backends = (do {
        plugin-kms-backends
    } | complete)

    assert ($backends.exit_code == 0)

    if ($backends.stdout | str length) > 0 {
        print $"    ✅ Backends detected: ($backends.stdout)"
    } else {
        print "    ⚠️  No backends available"
    }
}

# Test status check
export def test_kms_status [] {
    print "  Testing KMS status check..."

    use kms.nu *

    let status = (do {
        plugin-kms-status
    } | complete)

    assert ($status.exit_code == 0)

    if ($status.stdout | str length) > 0 {
        print "    ✅ Status check passed"
    } else {
        print "    ⚠️  Status check returned no data"
    }
}

# Test multiple backends
export def test_multiple_backends [] {
    print "  Testing multiple backends..."

    use kms.nu *

    let backends = ["age", "rustyvault", "vault"]
    let test_data = "Test data for backend comparison"

    for backend in $backends {
        let result = (do {
            plugin-kms-encrypt $test_data $backend
        } | complete)

        if $result.exit_code == 0 {
            print $"    ✅ Backend ($backend) working"
        } else {
            print $"    ⚠️  Backend ($backend) not available"
        }
    }
}

# Performance test (if plugin available)
export def test_kms_performance [] {
    print "  Testing KMS performance..."

    use kms.nu *

    # Check if plugin is available
    let has_plugin = (which kms | length) > 0

    let test_data = "Performance test data"

    # Run 5 iterations
    let times = (1..5 | each {|_|
        let start = (date now)
        let _ = (plugin-kms-encrypt $test_data "age" | complete)
        let end = (date now)
        ($end - $start | into duration | into int) / 1_000_000  # Convert to ms
    })

    let avg_time = ($times | math avg)
    let min_time = ($times | math min)
    let max_time = ($times | math max)

    print $"    Average: ($avg_time)ms, Min: ($min_time)ms, Max: ($max_time)ms"

    if $has_plugin and $avg_time < 50 {
        print "    ✅ Performance excellent (plugin active)"
    } else if $avg_time < 200 {
        print "    ✅ Performance good (likely HTTP fallback)"
    } else {
        print "    ⚠️  Performance slow (might be SOPS)"
    }
}

# Test configuration integration
export def test_config_integration [] {
    print "  Testing configuration integration..."

    # Should read KMS config values
    let config_check = (do {
        use ../config/accessor.nu *
        get-config-value "plugins.kms.enabled" true
    } | complete)

    assert ($config_check.exit_code == 0)

    # Check preferred backend
    let backend_check = (do {
        use ../config/accessor.nu *
        get-config-value "plugins.kms.preferred_backend" "age"
    } | complete)

    assert ($backend_check.exit_code == 0)
    print "    ✅ Configuration integration working"
}

# Test error handling
export def test_error_handling [] {
    print "  Testing error handling..."

    use kms.nu *

    # Test with empty data
    let result1 = (do {
        plugin-kms-encrypt "" "age"
    } | complete)

    # Should handle gracefully
    assert ($result1.exit_code == 0 or $result1.exit_code != 0)

    # Test with invalid backend
    let result2 = (do {
        plugin-kms-encrypt "test" "invalid_backend"
    } | complete)

    # Should fail gracefully
    if $result2.exit_code != 0 {
        assert ($result2.stderr | str length) > 0
        print "    ✅ Error handling working correctly"
    }
}

# Test file encryption (if test file exists)
export def test_file_encryption [] {
    print "  Testing file encryption..."

    use kms.nu *

    # Create temporary test file
    let test_file = "/tmp/kms_test_file.txt"
    let test_content = "This is test file content for KMS encryption"

    let file_result = (do {
        $test_content | save -f $test_file

        # Try to encrypt file
        let result = (do {
            plugin-kms-encrypt-file $test_file "age"
        } | complete)

        if $result.exit_code == 0 {
            print "    ✅ File encryption succeeded"

            # Cleanup
            rm -f $test_file
            rm -f $"($test_file).enc"
        } else {
            print "    ⚠️  File encryption not available"
        }
    } | complete)

    if $file_result.exit_code != 0 {
        print "    ⚠️  Could not create test file"
    }
}

# Main test runner
export def main [] {
    print "\n🧪 Running KMS Plugin Tests...\n"

    test_kms_plugin_available
    test_backend_detection
    test_kms_status
    test_encryption
    test_decryption
    test_encrypt_decrypt_roundtrip
    test_multiple_backends
    test_config_integration
    test_error_handling
    test_file_encryption
    test_kms_performance

    print "\n✅ KMS plugin tests completed!\n"
}
