<?php

namespace App\Support\Ssh;

use App\Models\Server;
use phpseclib3\Net\SSH2;
use RuntimeException;

/**
 * Thin wrapper around phpseclib SSH2 for command execution. The control plane
 * orchestrates real servers over SSH — it does not reimplement daemons.
 */
class SshClient
{
    use VerifiesHostKey;

    private ?SSH2 $ssh = null;

    public function __construct(
        private readonly CredentialVault $vault,
        private readonly int $timeout = 15,
        private readonly int $connectTimeout = 5,
    ) {}

    public function connect(Server $server): self
    {
        // Short, SEPARATE connect timeout so an unreachable / black-holing / tarpit host fails
        // fast (~5s) instead of holding the FPM worker for the full exec timeout. The
        // server-detail page issues several SSH reads in a row, so a dead host must not stack
        // timeout × N and exhaust workers (DoS). The exec/read timeout stays at 15s for
        // legitimately slow commands.
        $ssh = new SSH2($server->ip, $server->ssh_port ?: 22, $this->connectTimeout);
        $ssh->setTimeout($this->timeout);

        $this->verifyHostKey($ssh, $server);

        $login = $this->vault->resolve($server);

        if (! $ssh->login($login['username'], $login['secret'])) {
            throw new RuntimeException("SSH-Login auf {$server->name} ({$server->ip}) fehlgeschlagen.");
        }

        $this->ssh = $ssh;

        return $this;
    }

    public function exec(string $command): string
    {
        return (string) $this->client()->exec($command);
    }

    /**
     * Run a command and return [stdout, exitCode].
     *
     * @return array{0: string, 1: int|false}
     */
    public function run(string $command): array
    {
        $out = $this->exec($command);

        return [$out, $this->client()->getExitStatus()];
    }

    public function disconnect(): void
    {
        $this->ssh?->disconnect();
        $this->ssh = null;
    }

    private function client(): SSH2
    {
        return $this->ssh ?? throw new RuntimeException('Nicht verbunden — connect() zuerst aufrufen.');
    }
}
