<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\WebPush\Services\VapidKeyGenerator;

echo "=== VAPID Key Generator Test ===\n\n";

// Test 1: OpenSSL Extension Check
echo "Test 1: OpenSSL Extension Check\n";
if (! extension_loaded('openssl')) {
    echo "  ❌ OpenSSL extension not loaded\n";
    exit(1);
}
echo "  ✅ OpenSSL extension loaded\n\n";

// Test 2: Generate VAPID Key Pair
echo "Test 2: Generate VAPID Key Pair\n";

try {
    $generator = new VapidKeyGenerator();
    $keyPair = $generator->generate();

    echo "  ✅ Key pair generated successfully\n";
    echo "     Public Key Length:  " . strlen($keyPair->publicKey) . " chars\n";
    echo "     Private Key Length: " . strlen($keyPair->privateKey) . " chars\n\n";
} catch (\Exception $e) {
    echo "  ❌ Failed: {$e->getMessage()}\n";
    exit(1);
}

// Test 3: Validate Key Format
echo "Test 3: Validate Key Format\n";
$publicKeyValid = preg_match('/^[A-Za-z0-9_-]+$/', $keyPair->publicKey);
$privateKeyValid = preg_match('/^[A-Za-z0-9_-]+$/', $keyPair->privateKey);

if ($publicKeyValid && $privateKeyValid) {
    echo "  ✅ Keys are valid Base64 URL-safe encoded\n\n";
} else {
    echo "  ❌ Invalid key format\n";
    exit(1);
}

// Test 4: Display Keys in Different Formats
echo "Test 4: Display Keys\n\n";

echo "--- .env Format ---\n";
echo $keyPair->toEnvFormat();
echo "\n";

echo "--- JSON Format ---\n";
echo $keyPair->toJson();
echo "\n\n";

echo "--- Table Format ---\n";
echo "Public Key:  {$keyPair->publicKey}\n";
echo "Private Key: {$keyPair->privateKey}\n\n";

// Test 5: Generate Multiple Key Pairs (ensure uniqueness)
echo "Test 5: Generate Multiple Key Pairs (Uniqueness Check)\n";
$keyPair2 = $generator->generate();
$keyPair3 = $generator->generate();

if ($keyPair->publicKey !== $keyPair2->publicKey &&
    $keyPair2->publicKey !== $keyPair3->publicKey &&
    $keyPair->publicKey !== $keyPair3->publicKey) {
    echo "  ✅ Each generated key pair is unique\n\n";
} else {
    echo "  ❌ Generated keys are not unique\n";
    exit(1);
}

// Test 6: toArray() Method
echo "Test 6: toArray() Method\n";
$array = $keyPair->toArray();
if (isset($array['public_key']) && isset($array['private_key'])) {
    echo "  ✅ toArray() returns correct structure\n";
    echo "     Keys: " . implode(', ', array_keys($array)) . "\n\n";
} else {
    echo "  ❌ toArray() failed\n";
    exit(1);
}

echo "=== All Tests Passed! ✅ ===\n";
