<?php

namespace Modules\Bms\Console;

use Illuminate\Console\Command;
use Minishlink\WebPush\VAPID;

/**
 * Generates a VAPID key pair for BMS web-push. Copy the printed values into
 * .env as BMS_VAPID_PUBLIC_KEY / BMS_VAPID_PRIVATE_KEY.
 */
class VapidKeysCommand extends Command
{
    protected $signature = 'bms:vapid-keys';

    protected $description = 'Generate a VAPID key pair for BMS web-push';

    public function handle(): int
    {
        try {
            $keys = VAPID::createVapidKeys();
        } catch (\Throwable $e) {
            $this->error('Could not generate keys: ' . $e->getMessage());
            $this->warn('This usually means PHP openssl lacks EC (prime256v1) support on this host.');
            $this->line('Generate the pair on any host with proper openssl (or `npx web-push generate-vapid-keys`),');
            $this->line('then set BMS_VAPID_PUBLIC_KEY / BMS_VAPID_PRIVATE_KEY in .env.');
            return self::FAILURE;
        }

        $this->info('Add these to your .env:');
        $this->line('BMS_VAPID_PUBLIC_KEY=' . $keys['publicKey']);
        $this->line('BMS_VAPID_PRIVATE_KEY=' . $keys['privateKey']);

        return self::SUCCESS;
    }
}
