<?php

namespace App\Livewire\Modals;

use App\Models\AuditEvent;
use App\Models\Server;
use Illuminate\Support\Facades\Auth;
use LivewireUI\Modal\ModalComponent;

/**
 * Form modal: set/update a server's SSH credential (encrypted vault). This is
 * where an operator deposits e.g. a root/sudo login to enable service control.
 */
class EditCredential extends ModalComponent
{
    public int $serverId;

    public string $name = '';

    public string $username = '';

    public string $authType = 'password';

    public string $secret = '';

    public string $passphrase = '';

    public ?string $error = null;

    public function mount(int $serverId): void
    {
        // Depositing/updating a server's SSH login is a fleet-admin action.
        abort_unless(auth()->user()?->can('manage-fleet'), 403);

        $this->serverId = $serverId;

        if ($cred = Server::find($serverId)?->credential) {
            $this->name = $cred->name ?? '';
            $this->username = $cred->username;
            $this->authType = $cred->auth_type;
            // secret/passphrase are never pre-filled (encrypted at rest)
        }
    }

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

    public function save(): void
    {
        // Re-gate on save: refuse a demoted user / hand-crafted /livewire/update after mount.
        abort_unless(auth()->user()?->can('manage-fleet'), 403);

        $this->error = null;

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

            return;
        }
        if (trim($this->username) === '' || trim($this->secret) === '') {
            $this->error = __('modals.edit_credential.error_required');

            return;
        }
        if (mb_strlen(trim($this->name)) > 120) {
            $this->error = __('modals.edit_credential.error_name_too_long');

            return;
        }

        $server->credential()->updateOrCreate([], [
            'name' => trim($this->name) !== '' ? trim($this->name) : null,
            'username' => trim($this->username),
            'auth_type' => $this->authType === 'key' ? 'key' : 'password',
            'secret' => $this->secret,
            // A passphrase only applies to a private key; never store one for password auth.
            'passphrase' => ($this->authType === 'key' && $this->passphrase !== '') ? $this->passphrase : null,
        ]);

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

        $this->dispatch('credentialChanged');
        $this->dispatch('notify', message: __('modals.edit_credential.notify_saved'));
        $this->closeModal();
    }

    public function render()
    {
        return view('livewire.modals.edit-credential');
    }
}
