<?php

namespace Modules\PortalApi\Console;

use Illuminate\Console\Command;

/**
 * Generates a fresh VAPID keypair and prints the values to paste into
 * .env. Works without minishlink/web-push installed — uses raw openssl
 * to make a P-256 (prime256v1) keypair.
 *
 *   php artisan portal:push:keys
 */
class GenerateVapidKeysCommand extends Command
{
    protected $signature   = 'portal:push:keys';
    protected $description = 'Generate a VAPID keypair for the pet-owner PWA push notifications';

    public function handle(): int
    {
        if (! extension_loaded('openssl')) {
            $this->error('The openssl PHP extension is required.');
            return self::FAILURE;
        }

        $res = openssl_pkey_new([
            'curve_name'       => 'prime256v1',
            'private_key_type' => OPENSSL_KEYTYPE_EC,
        ]);
        if (! $res) {
            $this->error('openssl_pkey_new failed: ' . openssl_error_string());
            return self::FAILURE;
        }

        $details = openssl_pkey_get_details($res);
        $pub  = "\x04" . $details['ec']['x'] . $details['ec']['y'];          // uncompressed point
        $priv = $details['ec']['d'];

        $publicB64  = rtrim(strtr(base64_encode($pub),  '+/', '-_'), '=');
        $privateB64 = rtrim(strtr(base64_encode($priv), '+/', '-_'), '=');

        $this->newLine();
        $this->info('VAPID keypair generated. Paste these into your .env:');
        $this->newLine();
        $this->line("VAPID_PUBLIC_KEY=\"{$publicB64}\"");
        $this->line("VAPID_PRIVATE_KEY=\"{$privateB64}\"");
        $this->line('VAPID_SUBJECT="mailto:admin@yourclinic.com"');
        $this->newLine();
        $this->comment('Then run:');
        $this->line('  composer require minishlink/web-push');
        $this->line('  php artisan config:clear');
        $this->newLine();
        $this->comment('The PWA reads VAPID_PUBLIC_KEY via /api/v1/portal/push/key when subscribing.');

        return self::SUCCESS;
    }
}
