<?php

namespace App\Provisioning\Steps\Host;

use App\Models\ProvisioningRun;
use App\Provisioning\StepResult;
use App\Services\Ssh\RemoteShell;

/**
 * Installs Proxmox VE on the Debian base: add the no-subscription repo + key,
 * full-upgrade, install proxmox-ve. Long-running; apt/network failures retry,
 * a bad repo/key fails.
 */
class InstallProxmoxVe extends HostStep
{
    public function __construct(private RemoteShell $shell) {}

    public function key(): string
    {
        return 'install_proxmox_ve';
    }

    public function maxDuration(): int
    {
        return 1800;
    }

    public function execute(ProvisioningRun $run): StepResult
    {
        $host = $this->host($run);
        $this->keyLogin($this->shell, $host);

        // Idempotent: proxmox-ve already installed.
        if ($this->shell->run('dpkg -l proxmox-ve 2>/dev/null | grep -q "^ii"')->ok()) {
            return StepResult::advance();
        }

        $key = $this->shell->run(
            'curl -fsSL https://enterprise.proxmox.com/debian/proxmox-release-bookworm.gpg '.
            '-o /etc/apt/trusted.gpg.d/proxmox-release-bookworm.gpg'
        );
        if (! $key->ok()) {
            return StepResult::fail('Could not fetch the Proxmox release key.');
        }

        $this->shell->putFile(
            '/etc/apt/sources.list.d/pve-install-repo.list',
            "deb [arch=amd64] http://download.proxmox.com/debian/pve bookworm pve-no-subscription\n"
        );
        $this->shell->run('rm -f /etc/apt/sources.list.d/pve-enterprise.list');

        if (! $this->shell->run('export DEBIAN_FRONTEND=noninteractive; apt-get update')->ok()) {
            return StepResult::retry(60, 'apt-get update failed');
        }
        if (! $this->shell->run('export DEBIAN_FRONTEND=noninteractive; apt-get -y full-upgrade')->ok()) {
            return StepResult::retry(60, 'apt-get full-upgrade failed');
        }
        if (! $this->shell->run('export DEBIAN_FRONTEND=noninteractive; apt-get -y install proxmox-ve postfix open-iscsi')->ok()) {
            return StepResult::retry(60, 'proxmox-ve install failed');
        }

        return StepResult::advance();
    }
}
