<?php

namespace App\Livewire\Admin;

use App\Models\VpnPeer;
use App\Provisioning\Jobs\ApplyVpnPeer;
use LivewireUI\Modal\ModalComponent;

/**
 * Confirmation for revoking a VPN access for good (R5). Deleting a peer that
 * belongs to a host cuts CluPilot's own management path to that machine, so the
 * modal says so plainly rather than hiding the option.
 */
class ConfirmDeleteVpnPeer extends ModalComponent
{
    public string $uuid;

    public string $name = '';

    public ?string $hostName = null;

    public function mount(string $uuid): void
    {
        // Modals are reachable without the route middleware, so this is the
        // real guard, not a convenience check.
        $peer = VpnPeer::query()->with('host')->where('uuid', $uuid)->firstOrFail();
        $this->authorize('delete', $peer);
        $this->uuid = $uuid;
        $this->name = $peer->name;
        $this->hostName = $peer->host?->name;
    }

    public function delete(): void
    {
        $peer = VpnPeer::query()->where('uuid', $this->uuid)->first();
        if ($peer !== null) {
            $this->authorize('delete', $peer);

            // A tombstone that still carries a usable private key is a liability.
            $peer->purgeSecret();
            // Soft-delete, so the row survives as a tombstone until the hub has
            // actually dropped the peer. A hard delete here would let the next
            // sync adopt the still-present peer back as a live access —
            // silently restoring what was just revoked. ApplyVpnPeer purges the
            // tombstone once removal succeeded; SyncVpnPeers retries if not.
            $peer->delete();
            ApplyVpnPeer::dispatch($peer->public_key, null, false);
        }

        $this->dispatch('vpn-peer-deleted');
        $this->closeModal();
    }

    public function render()
    {
        return view('livewire.admin.confirm-delete-vpn-peer');
    }
}
