<?php

namespace App\Livewire\Admin;

use App\Models\Host;
use App\Provisioning\Jobs\PurgeHost;
use LivewireUI\Modal\ModalComponent;

/**
 * Confirmation for the destructive "remove host" action (R5). Deregisters the
 * CluPilot record only — it does not touch the physical server. The host is
 * deactivated immediately and purged asynchronously so removal never blocks on
 * (or races) an in-flight provisioning step.
 */
class ConfirmRemoveHost extends ModalComponent
{
    public string $uuid;

    public string $name = '';

    public function mount(string $uuid): void
    {
        $this->uuid = $uuid;
        $this->name = Host::query()->where('uuid', $uuid)->value('name') ?? '';
    }

    public function remove()
    {
        $this->authorize('hosts.manage');
        $host = Host::query()->where('uuid', $this->uuid)->first();

        if ($host !== null) {
            // Deactivate now (out of placement, visibly removed), finalize on the
            // provisioning worker which waits for the runner lock.
            $host->update(['status' => 'disabled']);
            PurgeHost::dispatch($host->uuid);
        }

        return $this->redirectRoute('admin.hosts', navigate: true);
    }

    public function render()
    {
        return view('livewire.admin.confirm-remove-host');
    }
}
