<?php

namespace App\Livewire\Servers;

use App\Models\Server;
use App\Models\TerminalSession;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Component;

/**
 * Per-server web terminal, rendered as the "Terminal" tab of the server-details page (the sidebar
 * Terminal page is the Clusev HOST shell instead). Mints a single-use token that the xterm.js island
 * uses to open a WebSocket to the terminal sidecar; this component never touches SSH or credentials.
 * A server shell is a day-to-day operator action (the host shell is the admin-only sidebar page).
 */
class ServerTerminal extends Component
{
    public Server $server;

    /** Mint a single-use token for this server and hand it to the xterm island via an event. */
    public function open(): void
    {
        abort_unless(Auth::user()?->can('operate'), 403);

        $token = Str::random(48);
        TerminalSession::create([
            'token' => $token,
            'user_id' => Auth::id(),
            'kind' => 'server',
            'server_id' => $this->server->id,
            'expires_at' => now()->addSeconds(60),
            'created_at' => now(),
        ]);

        $this->dispatch('terminal-open', token: $token, title: $this->server->name);
    }

    public function render()
    {
        return view('livewire.servers.server-terminal');
    }
}
