<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\CustomField\UserCustomFieldValueService;
use MintyPHP\Service\User\UserServicesFactory;

ApiBootstrap::init();
ApiResponse::requireMethod('GET');
$userAssignmentService = (new UserServicesFactory())->createUserAssignmentService();

$user = ApiAuth::user();
$userId = ApiAuth::userId();
$assignments = $userAssignmentService->buildAssignmentsForUser($userId);

$currentTenantId = (int) (ApiAuth::tenantId() ?? 0);
$currentTenant = $userAssignmentService->findTenantSummaryInAssignments($assignments, $currentTenantId);

$primaryTenantId = (int) ($user['primary_tenant_id'] ?? 0);
$primaryTenant = $userAssignmentService->findTenantSummaryInAssignments($assignments, $primaryTenantId);

$publicAssignments = $userAssignmentService->mapAssignmentsToPublic($assignments);
$canViewPermissions = ApiAuth::hasPermission(PermissionService::PERMISSIONS_VIEW);
$publicPermissions = $canViewPermissions ? ApiAuth::permissions() : [];
$publicCustomFields = UserCustomFieldValueService::buildPublicValuesByTenant(
    $userId,
    $assignments['tenants'] ?? [],
    ApiAuth::scopedTenantId()
);

ApiResponse::success([
    'data' => [
        'uuid' => $user['uuid'] ?? '',
        'first_name' => $user['first_name'] ?? '',
        'last_name' => $user['last_name'] ?? '',
        'display_name' => $user['display_name'] ?? '',
        'email' => $user['email'] ?? '',
        'job_title' => $user['job_title'] ?? '',
        'phone' => $user['phone'] ?? '',
        'mobile' => $user['mobile'] ?? '',
        'locale' => $user['locale'] ?? '',
        'current_tenant' => $currentTenant,
        'primary_tenant' => $primaryTenant,
        'can_view_permissions' => $canViewPermissions,
        'permissions' => $publicPermissions,
        'assignments' => $publicAssignments,
        'custom_fields' => $publicCustomFields,
    ],
]);
