<?php

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

ApiBootstrap::init();

$request = requestInput();
$method = $request->method();
$userServicesFactory = app(UserServicesFactory::class);
$userAssignmentService = $userServicesFactory->createUserAssignmentService();

if ($method === 'GET') {
    $user = ApiAuth::user();
    $userId = ApiAuth::userId();

    ApiResponse::success([
        'data' => buildMeResponse($user, $userId, $userAssignmentService),
    ]);
}

if ($method === 'PUT' || $method === 'PATCH') {
    ApiResponse::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_ME_SELF_UPDATE);

    $userId = ApiAuth::userId();
    $input = $request->bodyAll();

    $userAccountService = $userServicesFactory->createUserAccountService();
    $result = $userAccountService->updateSelfProfile($userId, $input);
    if (!($result['ok'] ?? false)) {
        $errors = $result['errors'] ?? [];
        if (is_array($errors) && $errors !== []) {
            ApiResponse::validationFromFormErrors(formErrors()->addMany('profile', array_values($errors)));
        }
        ApiResponse::fromServiceResult($result);
    }

    // Reload user after update
    $user = $userAccountService->findById($userId);
    if (!$user) {
        ApiResponse::error('update_failed', 500);
    }

    ApiResponse::success([
        'data' => buildMeResponse($user, $userId, $userAssignmentService),
    ]);
}

ApiResponse::methodNotAllowed();

/**
 * @param array<string, mixed> $user
 * @param int $userId
 * @param \MintyPHP\Service\User\UserAssignmentService $userAssignmentService
 * @return array<string, mixed>
 */
function buildMeResponse(array $user, int $userId, $userAssignmentService): array
{
    $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::can(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_PERMISSIONS_VIEW);
    $publicPermissions = $canViewPermissions ? ApiAuth::permissions() : [];
    $publicCustomFields = app(UserCustomFieldValueService::class)->buildPublicValuesByTenant(
        $userId,
        $assignments['tenants'] ?? [],
        ApiAuth::scopedTenantId()
    );

    return [
        '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'] ?? '',
        'theme' => $user['theme'] ?? '',
        'profile_description' => $user['profile_description'] ?? '',
        'short_dial' => $user['short_dial'] ?? '',
        'address' => $user['address'] ?? '',
        'postal_code' => $user['postal_code'] ?? '',
        'city' => $user['city'] ?? '',
        'country' => $user['country'] ?? '',
        'region' => $user['region'] ?? '',
        'current_tenant' => $currentTenant,
        'primary_tenant' => $primaryTenant,
        'can_view_permissions' => $canViewPermissions,
        'permissions' => $publicPermissions,
        'assignments' => $publicAssignments,
        'custom_fields' => $publicCustomFields,
    ];
}
