<?php

namespace Modules\ExternalSystem\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Modules\ExternalSystem\Entities\ExternalSystem;

class GenerateExternalSystemSsoSecretCommand extends Command
{
    protected $signature = 'external-system:generate-sso-secret
                            {code : External system code (e.g. e-vote)}
                            {--force : Replace an existing SSO secret}
                            {--length=64 : Secret length in characters}';

    protected $description = 'Generate an SSO secret for an external system and store it in the database';

    public function handle(): int
    {
        $code = (string) $this->argument('code');
        $length = max(32, (int) $this->option('length'));

        $system = ExternalSystem::query()->where('code', $code)->first();

        if (! $system) {
            $this->components->error("External system [{$code}] not found.");

            return self::FAILURE;
        }

        if (! $system->sso_enabled) {
            $this->components->warn("External system [{$code}] does not have SSO enabled.");
        }

        if (filled($system->sso_secret) && ! $this->option('force')) {
            $this->components->error('An SSO secret already exists. Use --force to replace it.');

            return self::FAILURE;
        }

        if (filled($system->sso_secret) && $this->option('force')) {
            if (! $this->confirm("Replace the existing SSO secret for [{$code}]?", false)) {
                $this->components->info('Aborted.');

                return self::SUCCESS;
            }
        }

        $secret = Str::password($length, symbols: true);

        $system->sso_secret = $secret;
        $system->save();

        $this->newLine();
        $this->components->info("SSO secret generated for [{$code}].");
        $this->newLine();
        $this->line('Copy this value into the external system environment:');
        $this->newLine();
        $this->line("  MYKOPKB_SSO_SECRET={$secret}");
        $this->newLine();
        $this->components->warn('This secret is shown once. Store it securely before closing this terminal.');

        return self::SUCCESS;
    }
}
