<?php

namespace App\Support;

use App\Models\AdminUser;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

/** 平台唯一超级管理员账号（不绑定站点）。 */
final class SuperAdminAccount
{
    public static function assign(AdminUser $user): AdminUser
    {
        return DB::transaction(function () use ($user): AdminUser {
            DB::table('admin_users')
                ->where('id', '!=', $user->id)
                ->update(['is_super_admin' => false]);

            $user->forceFill(['is_super_admin' => true])->save();

            self::removeLegacySiteRoleBinding((int) $user->id);

            return $user->fresh() ?? $user;
        });
    }

    public static function revoke(AdminUser $user): AdminUser
    {
        $user->forceFill(['is_super_admin' => false])->save();

        return $user->fresh() ?? $user;
    }

    public static function count(): int
    {
        return (int) AdminUser::query()->where('is_super_admin', true)->count();
    }

    public static function assertNotSiteRoleAssignment(array $roleSlugs): void
    {
        if (in_array(AdminUser::ROLE_SUPER_ADMIN, $roleSlugs, true)) {
            throw ValidationException::withMessages([
                'role_slugs' => [__('admin.super_admin_not_site_role')],
            ]);
        }
    }

    private static function removeLegacySiteRoleBinding(int $userId): void
    {
        $superRoleId = DB::table('admin_roles')
            ->where('slug', AdminUser::ROLE_SUPER_ADMIN)
            ->value('id');

        if ($superRoleId === null) {
            return;
        }

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