<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('pending_sync_queue', function (Blueprint $table) {
            $table->id();
            $table->foreignId('dns_zone_id')->constrained('dns_zones')->onDelete('cascade');
            $table->foreignId('nameserver_id')->constrained('name_servers')->onDelete('cascade');
            $table->enum('action', ['create', 'update', 'delete', 'full_sync'])->default('full_sync');
            $table->foreignId('dns_record_id')->nullable()->constrained('dns_records')->onDelete('cascade');
            $table->json('payload')->nullable(); // Date suplimentare pentru sync
            $table->integer('retry_count')->default(0);
            $table->integer('max_retries')->default(5);
            $table->timestamp('last_attempt_at')->nullable();
            $table->text('last_error')->nullable();
            $table->enum('status', ['pending', 'processing', 'failed', 'completed'])->default('pending');
            $table->enum('priority', ['low', 'normal', 'high'])->default('normal');
            $table->timestamps();

            // Index pentru căutări rapide
            $table->index(['nameserver_id', 'status']);
            $table->index(['dns_zone_id', 'status']);
            $table->index('status');
        });

        // Tabel pentru istoricul statusului nameserver-elor
        Schema::create('nameserver_status_history', function (Blueprint $table) {
            $table->id();
            $table->foreignId('nameserver_id')->constrained('name_servers')->onDelete('cascade');
            $table->enum('old_status', ['online', 'offline', 'maintenance', 'unknown'])->nullable();
            $table->enum('new_status', ['online', 'offline', 'maintenance', 'unknown']);
            $table->text('reason')->nullable();
            $table->integer('response_time_ms')->nullable();
            $table->timestamp('checked_at');
            $table->timestamps();

            $table->index(['nameserver_id', 'checked_at']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('nameserver_status_history');
        Schema::dropIfExists('pending_sync_queue');
    }
};
