<?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('clients', function (Blueprint $table) {
            if (! Schema::hasColumn('clients', 'portal_enabled')) {
                $table->boolean('portal_enabled')->default(true)->after('report_recipients');
            }

            if (! Schema::hasColumn('clients', 'portal_welcome_text')) {
                $table->text('portal_welcome_text')->nullable()->after('portal_enabled');
            }
        });

        Schema::table('client_user', function (Blueprint $table) {
            if (! Schema::hasColumn('client_user', 'is_active')) {
                $table->boolean('is_active')->default(true)->after('role');
            }

            if (! Schema::hasColumn('client_user', 'permissions')) {
                $table->json('permissions')->nullable()->after('is_active');
            }

            if (! Schema::hasColumn('client_user', 'last_portal_login_at')) {
                $table->timestamp('last_portal_login_at')->nullable()->after('permissions');
            }
        });
    }

    public function down(): void
    {
        Schema::table('client_user', function (Blueprint $table) {
            if (Schema::hasColumn('client_user', 'last_portal_login_at')) {
                $table->dropColumn('last_portal_login_at');
            }

            if (Schema::hasColumn('client_user', 'permissions')) {
                $table->dropColumn('permissions');
            }

            if (Schema::hasColumn('client_user', 'is_active')) {
                $table->dropColumn('is_active');
            }
        });

        Schema::table('clients', function (Blueprint $table) {
            if (Schema::hasColumn('clients', 'portal_welcome_text')) {
                $table->dropColumn('portal_welcome_text');
            }

            if (Schema::hasColumn('clients', 'portal_enabled')) {
                $table->dropColumn('portal_enabled');
            }
        });
    }
};
