<?php

namespace App\Support;

use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Models\AgentNode;
use Illuminate\Validation\ValidationException;

/** 经营代理主账号统一使用平台系统角色 {@see AdminRole} slug=agent。 */
final class AgentPlatformRole
{
    public static function resolve(): AdminRole
    {
        return AgentDefaultRolePermissions::ensurePlatformAgentRole();
    }

    public static function id(): int
    {
        $role = self::resolve();

        return (int) $role->id;
    }

    /** 主账号：仅绑定平台「代理」角色（权限在「平台角色管理」维护）。 */
    public static function assignPrimaryOperator(AdminUser $user, AgentNode $node): void
    {
        $user->syncAgentRoleIds((int) $node->id, [self::id()]);
    }

    public static function idOrFail(): int
    {
        $id = (int) (AdminRole::query()
            ->where('scope_type', AdminRole::SCOPE_SYSTEM)
            ->where('slug', 'agent')
            ->where('status', 1)
            ->value('id') ?? 0);

        if ($id <= 0) {
            throw ValidationException::withMessages([
                'role' => ['platform_agent_role_missing: run php artisan lottery:agent-roles-sync'],
            ]);
        }

        return $id;
    }
}
