<?php

namespace App\Provisioning\Jobs;

use App\Services\Wireguard\WireguardHub;
use Illuminate\Support\Facades\Cache;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

/**
 * Removes a host's WireGuard peer. Runs on the provisioning queue so it executes
 * in the privileged worker that owns the wg0 interface (the web container can't
 * manage WireGuard).
 */
class RemoveWireguardPeer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;

    public $timeout = 120;

    public function __construct(public string $publicKey)
    {
        $this->onConnection('provisioning');
        $this->onQueue('provisioning');
    }

    public function handle(WireguardHub $hub): void
    {
        // Every hub mutation takes this lock so SyncVpnPeers cannot read the
        // interface around it and then write what it saw — a peer removed here
        // would otherwise be reported back as a live access.
        Cache::lock('wireguard:hub', 30)->block(10, fn () => $hub->removePeer($this->publicKey));
    }
}
