<?php

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::table('mikrotiks', function (Blueprint $table) {
            if (! Schema::hasColumn('mikrotiks', 'ssl_enabled')) {
                $table->boolean('ssl_enabled')->default(false)->after('password');
            }
            if (! Schema::hasColumn('mikrotiks', 'is_default')) {
                $table->boolean('is_default')->default(false)->after('ssl_enabled');
            }
            if (! Schema::hasColumn('mikrotiks', 'connected')) {
                $table->boolean('connected')->default(false)->after('is_default');
            }
            if (! Schema::hasColumn('mikrotiks', 'last_connected_at')) {
                $table->timestamp('last_connected_at')->nullable()->after('connected');
            }
            if (! Schema::hasColumn('mikrotiks', 'last_checked_at')) {
                $table->timestamp('last_checked_at')->nullable()->after('last_connected_at');
            }
            if (! Schema::hasColumn('mikrotiks', 'response_time_ms')) {
                $table->unsignedInteger('response_time_ms')->nullable()->after('last_checked_at');
            }
        });

        Schema::table('packages', function (Blueprint $table) {
            if (! Schema::hasColumn('packages', 'mikrotik_server_id')) {
                $table->unsignedBigInteger('mikrotik_server_id')->nullable()->after('status');
                $table->index('mikrotik_server_id');
            }
            if (! Schema::hasColumn('packages', 'mikrotik_profile_name')) {
                $table->string('mikrotik_profile_name')->nullable()->after('mikrotik_server_id');
            }
        });
    }

    public function down(): void
    {
        Schema::table('mikrotiks', function (Blueprint $table) {
            $table->dropColumn(['ssl_enabled', 'is_default', 'connected', 'last_connected_at', 'last_checked_at', 'response_time_ms']);
        });

        Schema::table('packages', function (Blueprint $table) {
            $table->dropColumn(['mikrotik_server_id', 'mikrotik_profile_name']);
        });
    }
};
