<?php

namespace App\Support;

use App\Models\AdminUser;
use Illuminate\Http\Request;

final class AdminScopeContextResolver
{
    public static function fromRequest(
        Request $request,
        AdminUser $admin,
        string $siteParam = 'site_code',
        string $agentParam = 'agent_node_id',
    ): AdminScopeContext {
        $siteCode = $request->query($siteParam);
        $agentNodeId = $request->integer($agentParam) ?: null;

        return self::fromValues(
            $admin,
            is_string($siteCode) ? $siteCode : null,
            $agentNodeId,
        );
    }

    public static function fromValues(
        AdminUser $admin,
        ?string $requestedSiteCode = null,
        ?int $requestedAgentNodeId = null,
    ): AdminScopeContext {
        $siteCode = is_string($requestedSiteCode) ? trim($requestedSiteCode) : '';
        $agentNodeId = $requestedAgentNodeId !== null && $requestedAgentNodeId > 0
            ? $requestedAgentNodeId
            : null;

        return new AdminScopeContext(
            admin: $admin,
            requestedSiteCode: $siteCode !== '' ? $siteCode : null,
            requestedAgentNodeId: $agentNodeId,
        );
    }
}
