<?php

namespace App\Livewire\Modals;

use App\Models\AuditEvent;
use App\Models\Server;
use App\Services\FleetService;
use Illuminate\Support\Facades\Auth;
use LivewireUI\Modal\ModalComponent;
use phpseclib3\Crypt\EC;
use Throwable;

/**
 * Form modal: paste an SSH public key, append it to the server's authorized_keys
 * over SSH (real control), write an AuditEvent, and tell the page to reload.
 */
class AddSshKey extends ModalComponent
{
    public int $serverId;

    public string $publicKey = '';

    public ?string $generatedPrivate = null;

    public ?string $error = null;

    public function mount(int $serverId): void
    {
        $this->serverId = $serverId;
    }

    public static function modalMaxWidth(): string
    {
        return 'lg';
    }

    /** Generate a fresh ed25519 keypair: the public key is installed on save,
     *  the private key is shown once for the operator to store. */
    public function generate(): void
    {
        $this->error = null;
        $key = EC::createKey('ed25519');
        $this->publicKey = $key->getPublicKey()->toString('OpenSSH', ['comment' => 'clusev-key']);
        $this->generatedPrivate = (string) $key->toString('OpenSSH');
    }

    public function save(FleetService $fleet): void
    {
        $this->error = null;

        $server = Server::find($this->serverId);
        if (! $server) {
            $this->error = __('common.server_not_found');

            return;
        }

        try {
            $fleet->addAuthorizedKey($server, $this->publicKey);
        } catch (Throwable $e) {
            $this->error = $e->getMessage();

            return;
        }

        AuditEvent::create([
            'user_id' => Auth::id(),
            'server_id' => $server->id,
            'actor' => Auth::user()?->name ?? 'system',
            'action' => 'ssh_key.add',
            'target' => $server->name,
            'ip' => request()->ip(),
        ]);

        $this->dispatch('keyChanged');
        $this->dispatch('notify', message: __('modals.add_ssh_key.notify_added'));
        $this->closeModal();
    }

    public function render()
    {
        return view('livewire.modals.add-ssh-key');
    }
}
