<?php

declare(strict_types=1);

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

/**
 * Phase 3 — Cluster komünikasyon katmanı.
 *
 * 1. cluster_nodes'a HMAC secret + load/capacity + yeni alanlar eklenir.
 * 2. cluster_jobs tablosu (master → slave iş kuyruğu).
 * 3. cluster_heartbeats tablosu (son 24 saat heartbeat geçmişi).
 */
return new class extends Migration
{
    public function up(): void
    {
        // ── cluster_nodes extend ──────────────────────────────────────────────
        Schema::table('cluster_nodes', function (Blueprint $table) {
            if (! Schema::hasColumn('cluster_nodes', 'api_secret')) {
                $table->string('api_secret', 128)->nullable()
                    ->after('agent_token')
                    ->comment('Shared HMAC-SHA256 secret (plain, stored only on master)');
            }
            if (! Schema::hasColumn('cluster_nodes', 'ssh_public_key')) {
                $table->text('ssh_public_key')->nullable()->after('api_secret');
            }
            if (! Schema::hasColumn('cluster_nodes', 'os_version')) {
                $table->string('os_version', 100)->nullable()->after('ssh_public_key');
            }
            if (! Schema::hasColumn('cluster_nodes', 'panel_version')) {
                $table->string('panel_version', 50)->nullable()->after('os_version');
            }
            if (! Schema::hasColumn('cluster_nodes', 'capacity')) {
                $table->json('capacity')->nullable()->after('panel_version')
                    ->comment('{cpu_cores, ram_gb, storage_gb}');
            }
            if (! Schema::hasColumn('cluster_nodes', 'current_load')) {
                $table->json('current_load')->nullable()->after('capacity')
                    ->comment('{cpu_pct, mem_pct, disk_pct, accounts}');
            }
        });

        // ── cluster_jobs ─────────────────────────────────────────────────────
        Schema::create('cluster_jobs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('cluster_node_id')
                ->constrained('cluster_nodes')
                ->cascadeOnDelete();
            $table->string('action', 100)
                ->comment('sysapi action — e.g. user-add, domain-add');
            $table->json('payload');
            $table->enum('status', ['pending', 'claimed', 'running', 'completed', 'failed', 'cancelled'])
                ->default('pending');
            $table->json('result')->nullable();
            $table->text('error')->nullable();
            $table->unsignedInteger('attempts')->default(0);
            $table->timestamp('claimed_at')->nullable();
            $table->timestamp('started_at')->nullable();
            $table->timestamp('finished_at')->nullable();
            $table->unsignedInteger('duration_ms')->nullable();
            $table->foreignId('triggered_by')->nullable()->constrained('users');
            $table->timestamps();

            $table->index(['cluster_node_id', 'status']);
            $table->index(['status', 'created_at']);
        });

        // ── cluster_heartbeats (last-24h history) ────────────────────────────
        Schema::create('cluster_heartbeats', function (Blueprint $table) {
            $table->id();
            $table->foreignId('cluster_node_id')
                ->constrained('cluster_nodes')
                ->cascadeOnDelete();
            $table->json('load')->nullable()
                ->comment('{cpu_pct, mem_pct, disk_pct}');
            $table->unsignedInteger('accounts_count')->default(0);
            $table->timestamp('received_at');

            $table->index(['cluster_node_id', 'received_at']);
        });
    }

    public function down(): void
    {
        Schema::table('cluster_nodes', function (Blueprint $table) {
            $table->dropColumn(array_filter([
                Schema::hasColumn('cluster_nodes', 'api_secret') ? 'api_secret' : null,
                Schema::hasColumn('cluster_nodes', 'ssh_public_key') ? 'ssh_public_key' : null,
                Schema::hasColumn('cluster_nodes', 'os_version') ? 'os_version' : null,
                Schema::hasColumn('cluster_nodes', 'panel_version') ? 'panel_version' : null,
                Schema::hasColumn('cluster_nodes', 'capacity') ? 'capacity' : null,
                Schema::hasColumn('cluster_nodes', 'current_load') ? 'current_load' : null,
            ]));
        });

        Schema::dropIfExists('cluster_heartbeats');
        Schema::dropIfExists('cluster_jobs');
    }
};
