<?php

namespace App\Support;

use App\Models\AdminUser;
use App\Models\AgentNode;

final class AdminScopeContext
{
    public function __construct(
        public readonly AdminUser $admin,
        public readonly ?string $requestedSiteCode = null,
        public readonly ?int $requestedAgentNodeId = null,
    ) {}

    public function isSuperAdmin(): bool
    {
        return $this->admin->isSuperAdmin();
    }

    public function actorAgentNode(): ?AgentNode
    {
        return $this->admin->primaryAgentNode();
    }

    public function actorAgentNodeId(): ?int
    {
        $node = $this->actorAgentNode();

        return $node !== null ? (int) $node->id : null;
    }

    public function adminSiteId(): ?int
    {
        $node = $this->actorAgentNode();

        return $node !== null ? (int) $node->admin_site_id : null;
    }

    public function effectiveRequestedAgentNodeId(): ?int
    {
        return $this->requestedAgentNodeId !== null && $this->requestedAgentNodeId > 0
            ? $this->requestedAgentNodeId
            : null;
    }

    public function effectiveRequestedSiteCode(): ?string
    {
        $siteCode = is_string($this->requestedSiteCode) ? trim($this->requestedSiteCode) : '';

        return $siteCode !== '' ? $siteCode : null;
    }
}
