<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class GenerateVapidKeys extends Command
{
    protected $signature = 'push:generate-vapid';
    protected $description = 'Generate VAPID keys for Web Push notifications';

    public function handle()
    {
        $this->info('Generating VAPID keys...');
        
        try {
            // Try using the library first
            $keys = \Minishlink\WebPush\VAPID::createVapidKeys();
        } catch (\Exception $e) {
            // Fallback: generate using sodium if available
            if (function_exists('sodium_crypto_sign_keypair')) {
                $keys = $this->generateWithSodium();
            } else {
                $this->error('Failed to generate VAPID keys: ' . $e->getMessage());
                $this->newLine();
                $this->info('You can generate VAPID keys online at:');
                $this->line('https://vapidkeys.com/');
                return 1;
            }
        }

        $this->newLine();
        $this->info('Add these to your .env file:');
        $this->newLine();
        
        $this->line('VAPID_PUBLIC_KEY=' . $keys['publicKey']);
        $this->line('VAPID_PRIVATE_KEY=' . $keys['privateKey']);

        $this->newLine();
        $this->info('Also add to .env for frontend (Vite):');
        $this->line('VITE_VAPID_PUBLIC_KEY="${VAPID_PUBLIC_KEY}"');

        return 0;
    }

    /**
     * Generate VAPID keys using Sodium (libsodium).
     */
    protected function generateWithSodium(): array
    {
        $keyPair = sodium_crypto_sign_keypair();
        $publicKey = sodium_crypto_sign_publickey($keyPair);
        $privateKey = sodium_crypto_sign_secretkey($keyPair);

        return [
            'publicKey' => rtrim(strtr(base64_encode($publicKey), '+/', '-_'), '='),
            'privateKey' => rtrim(strtr(base64_encode(substr($privateKey, 0, 32)), '+/', '-_'), '='),
        ];
    }
}
