<?php

namespace App\Provisioning\Steps\Customer;

use App\Models\ProvisioningRun;
use App\Provisioning\StepResult;
use App\Services\Proxmox\ProxmoxClient;

class StartVirtualMachine extends CustomerStep
{
    public function __construct(private ProxmoxClient $pve) {}

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

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

    public function execute(ProvisioningRun $run): StepResult
    {
        $instance = $this->instance($run);
        $node = (string) $run->context('node');
        $vmid = (int) $run->context('vmid');
        $pve = $this->pve->forHost($instance->host);

        // Idempotent: already running.
        if (($pve->vmStatus($node, $vmid)['status'] ?? '') === 'running') {
            return StepResult::advance();
        }

        $upid = $run->context('start_upid');
        if ($upid === null) {
            $upid = $pve->startVm($node, $vmid);
            $run->mergeContext(['start_upid' => $upid]);
        }

        $task = $pve->taskStatus($node, $upid);
        if (($task['status'] ?? '') === 'running') {
            return StepResult::poll(5, 'starting VM');
        }
        if (($task['exitstatus'] ?? 'OK') !== 'OK') {
            return StepResult::fail('start_failed: '.($task['exitstatus'] ?? 'unknown'));
        }

        return StepResult::advance();
    }
}
