<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * VPN accesses on the management hub. Two kinds share this table:
 * operator accesses created in the console, and the peers the host pipeline
 * registers for Proxmox hosts (linked via host_id). The console lists both,
 * because "who is connected to the VPN" must not have blind spots.
 *
 * `enabled` is the DESIRED state (operator intent), `present` the OBSERVED
 * state on the interface, refreshed by SyncVpnPeers. Keeping them apart makes
 * drift visible instead of silently overwriting what the operator asked for.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('vpn_peers', function (Blueprint $table) {
            $table->id();
            $table->uuid()->unique();                       // R11: UUIDs in URLs
            $table->string('name');
            $table->string('public_key')->unique();
            $table->string('allowed_ip')->unique();         // one tunnel address per peer
            $table->foreignId('host_id')->nullable()->constrained()->nullOnDelete();
            $table->boolean('enabled')->default(true);
            $table->boolean('present')->default(false);
            $table->string('endpoint')->nullable();         // last source address seen
            $table->timestamp('last_handshake_at')->nullable();
            $table->unsignedBigInteger('rx_bytes')->default(0);
            $table->unsignedBigInteger('tx_bytes')->default(0);
            $table->timestamp('observed_at')->nullable();   // when the hub last reported it
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            // Tombstone: a revoked access keeps its row until the hub has
            // actually dropped the peer. Deleting outright would let the next
            // sync see the still-present peer and adopt it back as a live
            // access — silently restoring what an operator just revoked.
            $table->softDeletes();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('vpn_peers');
    }
};
