<?php

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('admin_users', function (Blueprint $table): void {
            $table->boolean('is_super_admin')->default(false)->after('status');
        });

        $superRoleId = DB::table('admin_roles')->where('slug', 'super_admin')->value('id');
        if ($superRoleId !== null) {
            $superUserIds = DB::table('admin_user_site_roles')
                ->where('role_id', $superRoleId)
                ->distinct()
                ->pluck('admin_user_id');

            foreach ($superUserIds as $userId) {
                DB::table('admin_users')
                    ->where('id', $userId)
                    ->update(['is_super_admin' => true]);
            }

            DB::table('admin_user_site_roles')
                ->where('role_id', $superRoleId)
                ->delete();
        }

        // 仅允许一名超管：若历史数据误绑多名，保留最小 id。
        $superAdminIds = DB::table('admin_users')
            ->where('is_super_admin', true)
            ->orderBy('id')
            ->pluck('id');

        if ($superAdminIds->count() > 1) {
            $keepId = (int) $superAdminIds->first();
            DB::table('admin_users')
                ->where('is_super_admin', true)
                ->where('id', '!=', $keepId)
                ->update(['is_super_admin' => false]);
        }

        $driver = Schema::getConnection()->getDriverName();
        if ($driver === 'pgsql') {
            DB::statement('CREATE UNIQUE INDEX admin_users_single_super_admin ON admin_users (is_super_admin) WHERE is_super_admin = true');
        } elseif ($driver === 'sqlite') {
            DB::statement('CREATE UNIQUE INDEX admin_users_single_super_admin ON admin_users (is_super_admin) WHERE is_super_admin = 1');
        }
    }

    public function down(): void
    {
        $driver = Schema::getConnection()->getDriverName();
        if (in_array($driver, ['pgsql', 'sqlite'], true)) {
            DB::statement('DROP INDEX IF EXISTS admin_users_single_super_admin');
        }

        Schema::table('admin_users', function (Blueprint $table): void {
            $table->dropColumn('is_super_admin');
        });
    }
};
