<?php

namespace App\Support;

use App\Models\AdminSite;
use App\Models\AdminUser;
use App\Models\AgentNode;
use App\Models\AgentProfile;

final class AdminAuthProfile
{
    /**
     * @return array{
     *   id: int,
     *   username: string,
     *   nickname: string,
     *   email: ?string,
     *   permissions: list<string>,
     *   navigation: list<array{
     *     segment: string,
     *     label: string,
     *     href: string,
     *     nav_group: string,
     *     platform_only?: bool,
     *     agent_hidden?: bool,
     *     activeMatchPrefix?: string,
     *     requiredAny?: list<string>
     *   }>,
     *   agent: ?array{
     *     id: int,
     *     admin_site_id: int,
     *     admin_site_name: string,
     *     site_code: string,
     *     path: string,
     *     code: string,
     *     name: string,
     *     depth: int,
     *     can_create_child_agent: bool,
     *     can_create_player: bool
     *   },
     *   site: ?array{id: int, code: string, name: string},
     *   is_super_admin: bool,
     *   account_kind: 'super_admin'|'site_admin'|'site_finance'|'site_cs'|'agent_operator'|'platform_account',
     *   operational_permissions: list<string>,
     *   delegation_ceiling: list<string>,
     *   accessible_sites?: list<array{id: int, code: string, name: string}>
     * }
     */
    public static function fromAdmin(AdminUser $admin): array
    {
        $fresh = $admin->fresh();
        $permissionSlugs = $fresh->adminPermissionSlugs();
        $operationalCodes = $fresh->effectiveMenuActionPermissionCodes();
        $agent = self::agentContext($fresh);

        $payload = [
            'id' => $fresh->id,
            'username' => $fresh->username,
            'nickname' => $fresh->name,
            'email' => $fresh->email,
            'permissions' => $permissionSlugs,
            'navigation' => AdminAuthorizationRegistry::visibleNavigationItems($permissionSlugs, $fresh),
            'agent' => $agent,
            'site' => self::siteContext($fresh),
            'is_super_admin' => $fresh->isSuperAdmin(),
            'account_kind' => self::accountKind($fresh),
            'operational_permissions' => $operationalCodes,
            'delegation_ceiling' => AgentDelegationAuthorization::delegationLegacySlugsForAdminUser($fresh),
        ];

        if ($agent === null) {
            $payload['accessible_sites'] = AdminUserSiteBindingPresenter::accessibleSitesFor($fresh);
        }

        return $payload;
    }

    /**
     * @return array{id: int, code: string, name: string}|null
     */
    private static function siteContext(AdminUser $admin): ?array
    {
        if ($admin->isSuperAdmin() || $admin->primaryAgentNode() !== null) {
            return null;
        }

        if (! SiteOperatorRoles::userHasSiteOperatorRole($admin)) {
            return null;
        }

        $sites = AdminUserSiteBindingPresenter::accessibleSitesFor($admin);
        if ($sites === []) {
            return null;
        }

        $site = $sites[0];

        return [
            'id' => (int) $site['id'],
            'code' => (string) $site['code'],
            'name' => (string) $site['name'],
        ];
    }

    private static function agentContext(AdminUser $admin): ?array
    {
        if ($admin->isSuperAdmin()) {
            return null;
        }

        $node = $admin->primaryAgentNode();
        if (! $node instanceof AgentNode) {
            return null;
        }

        $site = AdminSite::query()
            ->where('id', (int) $node->admin_site_id)
            ->first(['code', 'name']);
        $siteCode = is_string($site?->code) ? $site->code : '';
        $siteName = is_string($site?->name) ? $site->name : '';
        $profile = AgentProfile::query()->where('agent_node_id', $node->id)->first();

        return [
            'id' => (int) $node->id,
            'admin_site_id' => (int) $node->admin_site_id,
            'admin_site_name' => $siteName,
            'site_code' => $siteCode !== '' ? $siteCode : '',
            'path' => (string) $node->path,
            'code' => (string) $node->code,
            'name' => (string) $node->name,
            'depth' => (int) $node->depth,
            'can_create_child_agent' => (bool) ($profile?->can_create_child_agent ?? false),
            'can_create_player' => (bool) ($profile?->can_create_player ?? false),
        ];
    }

    private static function accountKind(AdminUser $admin): string
    {
        if ($admin->isSuperAdmin()) {
            return 'super_admin';
        }

        if ($admin->hasPrimaryAgentBinding()) {
            return 'agent_operator';
        }

        $siteRole = SiteOperatorRoles::primarySiteOperatorSlug($admin);
        if ($siteRole !== null) {
            return $siteRole;
        }

        return 'platform_account';
    }
}
