<?php

namespace PloverCRM\Core\Services;

use PloverCRM\Common\CrmUserManager;
use PloverCRM\Common\RoleManager;

/**
 * Builds the canonical current-user payload shared by the hosted app and APIs.
 */
class CurrentUserPayloadBuilder
{
    public static function build(?\WP_User $wpUser = null): ?array
    {
        $wpUser = $wpUser ?: wp_get_current_user();

        if (!$wpUser || !$wpUser->ID) {
            return null;
        }

        $profile = CrmUserManager::getPublicProfileByWordPressUserId((int) $wpUser->ID);
        $accessContext = RoleManager::getUserAccessContext($wpUser->ID);

        return [
            'id' => (int) ($profile['id'] ?? $wpUser->ID),
            'crm_user_id' => (int) ($profile['id'] ?? $wpUser->ID),
            'wp_user_id' => (int) $wpUser->ID,
            'username' => $profile['username'] ?? $wpUser->user_login,
            'email' => $profile['email'] ?? $wpUser->user_email,
            'display_name' => $profile['display_name'] ?? $wpUser->display_name,
            'avatar_url' => $profile['avatar_url'] ?? null,
            'avatar_source' => $profile['avatar_source'] ?? CrmUserManager::AVATAR_SOURCE_NONE,
            'assigned_role' => $accessContext['assigned_role'],
            'effective_role' => $accessContext['effective_role'],
            'access' => $accessContext['access'],
        ];
    }
}
