<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('replication_setups', function (Blueprint $table) {
            $table->id();
            $table->enum('service_type', ['mariadb', 'powerdns', 'redis']);
            $table->enum('topology', ['master-slave', 'master-master', 'sentinel', 'galera'])->default('master-slave');
            $table->foreignId('master_node_id')->constrained('cluster_nodes')->cascadeOnDelete();
            $table->json('slave_node_ids');          // [N, N, ...]
            $table->enum('status', ['planned', 'configuring', 'active', 'failed', 'degraded', 'paused'])->default('planned');
            $table->json('config_snapshot')->nullable(); // captured config at setup time
            $table->timestamp('last_health_check_at')->nullable();
            $table->json('health_status')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users');
            $table->timestamps();
            $table->index(['service_type', 'status']);
        });

        Schema::create('replication_failover_events', function (Blueprint $table) {
            $table->id();
            $table->foreignId('replication_setup_id')->constrained('replication_setups')->cascadeOnDelete();
            $table->enum('event_type', ['lag_detected', 'master_down', 'auto_failover', 'manual_failover', 'recovery', 'promotion']);
            $table->foreignId('previous_master_id')->nullable()->constrained('cluster_nodes')->nullOnDelete();
            $table->foreignId('new_master_id')->nullable()->constrained('cluster_nodes')->nullOnDelete();
            $table->json('details')->nullable();
            $table->boolean('automatic')->default(false);
            $table->timestamp('occurred_at')->useCurrent();
            $table->timestamps();
        });
    }

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