<?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
    {
        $hasSuperAdmin = Schema::hasColumn('admins', 'is_super_admin');
        $hasPermissions = Schema::hasColumn('admins', 'project_permissions');

        if ($hasSuperAdmin && $hasPermissions) {
            return;
        }

        Schema::table('admins', function (Blueprint $table) use ($hasSuperAdmin, $hasPermissions) {
            if (!$hasSuperAdmin) {
                $table->boolean('is_super_admin')->default(true)->after('password');
            }

            if (!$hasPermissions) {
                $table->text('project_permissions')->nullable()->after('is_super_admin');
            }
        });
    }

    public function down(): void
    {
        $hasSuperAdmin = Schema::hasColumn('admins', 'is_super_admin');
        $hasPermissions = Schema::hasColumn('admins', 'project_permissions');

        if (!$hasSuperAdmin && !$hasPermissions) {
            return;
        }

        Schema::table('admins', function (Blueprint $table) use ($hasSuperAdmin, $hasPermissions) {
            if ($hasPermissions) {
                $table->dropColumn('project_permissions');
            }

            if ($hasSuperAdmin) {
                $table->dropColumn('is_super_admin');
            }
        });
    }
};
