<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('is_primary_admin')->default(false)->after('status');
        });

        $superAdminRole = config('permissions.super_admin_role', 'Super Admin');

        $roleId = DB::table('roles')
            ->where('name', $superAdminRole)
            ->where('guard_name', config('permissions.guard', 'web'))
            ->value('id');

        if ($roleId) {
            $primaryUserId = DB::table('model_has_roles')
                ->where('role_id', $roleId)
                ->where('model_type', User::class)
                ->orderBy('model_id')
                ->value('model_id');

            if ($primaryUserId) {
                DB::table('users')
                    ->where('id', $primaryUserId)
                    ->update(['is_primary_admin' => true]);
            }
        }
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('is_primary_admin');
        });
    }
};
