<?php

namespace App\Provisioning\Steps\Customer;

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

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

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

    public function maxDuration(): int
    {
        // Above the 270s own-deadline below, so the step's own fail fires first.
        return 360;
    }

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

        if ($this->pve->forHost($instance->host)->guestAgentPing($node, $vmid)) {
            return StepResult::advance();
        }

        // Own deadline (poll doesn't consume the retry budget).
        if ($run->started_at !== null && $run->started_at->copy()->addSeconds(270)->isPast()) {
            return StepResult::fail('guest_agent_timeout');
        }

        return StepResult::poll(10, 'waiting for guest agent');
    }
}
