<?php

namespace App\Provisioning\Steps\Customer;

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

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

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

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

    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: setting the same values / resizing to a size not smaller is a no-op.
        $pve->setCloudInit($node, $vmid, [
            'ipconfig0' => 'ip=dhcp',
            'ciuser' => 'clupilot',
            'nameserver' => '1.1.1.1',
            'cores' => $instance->cores,      // apply the plan's CPU/RAM, not the template's
            'memory' => $instance->ram_mb,
        ]);
        // Absolute target (not '+…') so a retry can't grow the disk twice.
        $pve->resizeDisk($node, $vmid, 'scsi0', $instance->disk_gb.'G');

        return StepResult::advance();
    }
}
