<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Helpers\LicenseManager;
use Illuminate\Console\Command;

class GenerateLicenseKey extends Command
{
    protected $signature = 'license:generate
        {--name= : Licensee name}
        {--email= : Licensee email address}
        {--product= : Product name}
        {--type= : License type (single, unlimited)}
        {--expires= : Expiry date in YYYY-MM-DD format (omit for perpetual)}
        {--save : Write the key to storage/app/license.key}';

    protected $description = 'Generate a signed license key (development/bootstrapping only — production keys are issued by the external licensing application)';

    public function handle(): int
    {
        $name = $this->option('name') ?? $this->ask('Licensee name', 'Development License');
        $email = $this->option('email') ?? $this->ask('Licensee email address', 'test@mailinator.com');
        $product = $this->option('product') ?? $this->ask('Product name (leave blank to omit)', 'Development Application');
        $type = $this->option('type') ?? $this->choice('License type', ['unlimited', 'single'], 'unlimited');
        $expires = $this->option('expires') ?? $this->ask('Expiry date (YYYY-MM-DD, leave blank for perpetual)');

        $payload = array_filter([
            'name' => $name,
            'email' => $email,
            'product' => $product ?: null,
            'type' => $type,
            'issued' => now()->toDateString(),
            'expires' => $expires ?: null,
        ], fn ($v) => $v !== null);

        try {
            $key = LicenseManager::generate($payload);
        } catch (\RuntimeException $e) {
            $this->error('Key generation failed: '.$e->getMessage());

            return self::FAILURE;
        }

        $this->newLine();
        $this->info('Generated license key:');
        $this->newLine();
        $this->line($key);
        $this->newLine();

        if ($this->option('save') || $this->confirm('Save this key to storage/app/license.key?', false)) {
            LicenseManager::store($key);
            $this->info('Key saved to storage/app/license.key');
        }

        return self::SUCCESS;
    }
}
