<?php

namespace App\Support;

use App\Models\AdminSite;
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;

final class AdminAgentNodeAccess
{
    public static function resolveAdminSiteId(AdminUser $admin, ?int $requestedSiteId): ?int
    {
        if ($admin->isSuperAdmin()) {
            if ($requestedSiteId !== null && $requestedSiteId > 0) {
                return $requestedSiteId;
            }

            return (int) (AdminSite::query()->where('is_default', true)->value('id')
                ?? AdminSite::query()->orderBy('id')->value('id'));
        }

        // Agent account (bound via agent node) - check first
        $actor = AdminAgentScope::primaryAgentNode($admin);
        if ($actor !== null) {
            if ($requestedSiteId !== null && $requestedSiteId > 0 && $requestedSiteId !== (int) $actor->admin_site_id) {
                return null;
            }

            return (int) $actor->admin_site_id;
        }

        if (! AdminAgentScope::isSiteOnlyOperator($admin)) {
            return null;
        }

        $accessibleSiteIds = $admin->accessibleAdminSiteIds() ?? [];
        if ($requestedSiteId !== null && $requestedSiteId > 0) {
            if (in_array($requestedSiteId, $accessibleSiteIds, true)) {
                return $requestedSiteId;
            }

            return null;
        }

        return $accessibleSiteIds[0] ?? null;
    }

    public static function denyUnlessSiteResolved(AdminUser $admin, ?int $siteId): ?JsonResponse
    {
        if ($siteId !== null && $siteId > 0) {
            return null;
        }

        return ApiMessage::errorResponse(
            request(),
            'admin.agent_site_access_denied',
            ErrorCode::AdminForbidden->value,
            null,
            403,
        );
    }

    public static function denyUnlessNodeVisible(AdminUser $admin, AgentNode $node): ?JsonResponse
    {
        if (AdminAgentScope::nodeVisibleTo($admin, $node)) {
            return null;
        }

        return ApiMessage::errorResponse(
            request(),
            'admin.agent_node_access_denied',
            ErrorCode::AdminForbidden->value,
            null,
            403,
        );
    }

    public static function denyUnlessCanManageParent(AdminUser $admin, AgentNode $parent): ?JsonResponse
    {
        if (! AdminAgentScope::nodeManageableBy($admin, $parent)) {
            return ApiMessage::errorResponse(
                request(),
                'admin.agent_node_manage_denied',
                ErrorCode::AdminForbidden->value,
                null,
                403,
            );
        }

        // Only pure platform accounts (site admin without agent binding) can create under root node
        // Agent accounts (even if they also have site roles) are restricted from creating under root
        if ($parent->isRoot() && ! $admin->isSuperAdmin()) {
            $accessibleSiteIds = $admin->accessibleAdminSiteIds();
            $hasAgentBinding = AdminAgentScope::primaryAgentNode($admin) !== null;
            
            // If user has agent binding, treat as agent account and restrict root creation
            if ($hasAgentBinding || $accessibleSiteIds === null) {
                return ApiMessage::errorResponse(
                    request(),
                    'admin.agent_root_create_denied',
                    ErrorCode::AdminForbidden->value,
                    null,
                    403,
                );
            }
        }

        return null;
    }
}
