<?php

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

return new class extends Migration
{
    /**
     * PRC-95 — local cache for DNS zones + records.
     *
     * The driver provider is the source of truth; these tables let the
     * admin/clientarea browse + edit without round-tripping the API on
     * every page load, and provide an audit trail.
     */
    public function up(): void
    {
        Schema::create('dns_zones', function (Blueprint $table) {
            $table->id();
            $table->string('domain', 255);   // example.com (no trailing dot)
            $table->string('provider', 50);   // cloudflare | powerdns | ...
            $table->string('provider_zone_id', 255);
            $table->unsignedBigInteger('client_id')->nullable();
            $table->unsignedBigInteger('client_domain_id')->nullable();
            $table->string('status', 20)->default('active');   // active | suspended | error
            $table->timestamp('last_synced_at')->nullable();
            $table->timestamps();

            $table->unique(['provider', 'provider_zone_id']);
            $table->index('domain');
            $table->index(['client_id']);
            $table->index(['client_domain_id']);
        });

        Schema::create('dns_records', function (Blueprint $table) {
            $table->id();
            $table->foreignId('zone_id')->constrained('dns_zones')->cascadeOnDelete();
            $table->string('provider_record_id', 255)->nullable();   // CF record uuid OR composite name|type for PDNS
            $table->string('type', 10);   // A, AAAA, CNAME, MX, TXT, ...
            $table->string('name', 255);
            $table->text('content');
            $table->unsignedInteger('ttl')->default(3600);
            $table->unsignedSmallInteger('priority')->nullable();   // MX/SRV
            $table->boolean('proxied')->default(false);   // Cloudflare-only
            $table->timestamps();

            $table->index(['zone_id', 'type', 'name']);
        });
    }

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