<?php

declare(strict_types=1);

namespace App\Framework\WebPush\Console;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ConsoleInput;
use App\Framework\Console\ExitCode;
use App\Framework\WebPush\Services\VapidKeyGenerator;

/**
 * VAPID Key Console Commands.
 */
final readonly class VapidKeyCommands
{
    public function __construct(
        private VapidKeyGenerator $generator
    ) {
    }

    #[ConsoleCommand(name: 'vapid:generate', description: 'Generate VAPID keys for Web Push Notifications')]
    public function generate(ConsoleInput $input): int
    {
        $format = $input->getOption('format') ?? 'env';
        $validFormats = ['env', 'json', 'table'];

        if (! in_array($format, $validFormats, true)) {
            echo "❌ Invalid format. Valid formats: " . implode(', ', $validFormats) . "\n";

            return ExitCode::GENERAL_ERROR->value;
        }

        echo "Generating VAPID key pair...\n\n";

        try {
            $keyPair = $this->generator->generate();
        } catch (\RuntimeException $e) {
            echo "❌ Failed to generate VAPID keys: {$e->getMessage()}\n";

            return ExitCode::GENERAL_ERROR->value;
        }

        echo "✅ VAPID keys generated successfully!\n\n";

        match ($format) {
            'env' => $this->displayEnvFormat($keyPair),
            'json' => $this->displayJsonFormat($keyPair),
            'table' => $this->displayTableFormat($keyPair),
        };

        echo "\n";
        echo "ℹ️  Add these keys to your .env file for Web Push Notifications.\n";
        echo "ℹ️  The public key should be shared with your frontend application.\n";
        echo "ℹ️  The private key must remain secret on your server.\n";

        return ExitCode::SUCCESS->value;
    }

    /**
     * Zeigt Keys im .env Format.
     */
    private function displayEnvFormat($keyPair): void
    {
        echo "--- .env Format ---\n\n";
        echo $keyPair->toEnvFormat();
    }

    /**
     * Zeigt Keys im JSON Format.
     */
    private function displayJsonFormat($keyPair): void
    {
        echo "--- JSON Format ---\n\n";
        echo $keyPair->toJson();
        echo "\n";
    }

    /**
     * Zeigt Keys im Table Format.
     */
    private function displayTableFormat($keyPair): void
    {
        echo "--- VAPID Key Pair ---\n\n";
        echo "Public Key:\n";
        echo "  {$keyPair->publicKey}\n\n";
        echo "Private Key:\n";
        echo "  {$keyPair->privateKey}\n";
    }
}
