<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Access\AuthorizationDecision;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Service\CustomField\UserCustomFieldValueService;
use MintyPHP\Service\User\UserAccountService;
use MintyPHP\Service\User\UserApiWriteInputMapper;
use MintyPHP\Service\User\UserAssignmentService;

ApiBootstrap::init();
$request = requestInput();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$userAccountService = app(UserAccountService::class);
$userAssignmentService = app(UserAssignmentService::class);
$userRoleRepository = app(\MintyPHP\Repository\Access\UserRoleRepository::class);
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
$apiDeny = static function (AuthorizationDecision $decision): void {
    if ($decision->isAllowed()) {
        return;
    }

    $status = $decision->status();
    $error = $decision->error() !== '' ? $decision->error() : 'forbidden';

    if ($status === 401) {
        ApiResponse::unauthorized();
    }
    if ($status === 404) {
        ApiResponse::notFound($error);
    }
    if ($status === 403) {
        ApiResponse::forbidden($error);
    }

    ApiResponse::error($error, $status > 0 ? $status : 403);
};

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    ApiResponse::notFound();
}

$method = $request->method();

if ($method === 'GET') {
    $user = $userAccountService->findByUuid($uuid);
    $userId = (int) ($user['id'] ?? 0);
    $decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_GET, [
        'actor_user_id' => ApiAuth::userId(),
        'target_user_id' => $userId,
        'scoped_tenant_id' => ApiAuth::scopedTenantId(),
    ]);
    $apiDeny($decision);
    if (!$user) {
        ApiResponse::notFound();
    }

    $assignments = $userAssignmentService->buildAssignmentsForUser($userId);
    $currentTenantId = (int) ($user['current_tenant_id'] ?? 0);
    $currentTenant = $userAssignmentService->findTenantSummaryInAssignments($assignments, $currentTenantId);
    $primaryTenantId = (int) ($user['primary_tenant_id'] ?? 0);
    $primaryTenant = $userAssignmentService->findTenantSummaryInAssignments($assignments, $primaryTenantId);
    $publicAssignments = $userAssignmentService->mapAssignmentsToPublic($assignments);
    $publicCustomFields = app(UserCustomFieldValueService::class)->buildPublicValuesByTenant(
        $userId,
        $assignments['tenants'] ?? [],
        ApiAuth::scopedTenantId()
    );
    $publicPermissions = [];
    if (ApiAuth::can(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_API_PERMISSIONS_VIEW)) {
        $roleIds = $userRoleRepository->listRoleIdsByUserId($userId);
        $publicPermissions = $rolePermissionRepository->listPermissionKeysByRoleIds($roleIds);
    }

    ApiResponse::success([
        'data' => [
            'uuid' => $user['uuid'] ?? '',
            'first_name' => $user['first_name'] ?? '',
            'last_name' => $user['last_name'] ?? '',
            'display_name' => $user['display_name'] ?? '',
            'email' => $user['email'] ?? '',
            'profile_description' => $user['profile_description'] ?? '',
            'job_title' => $user['job_title'] ?? '',
            'phone' => $user['phone'] ?? '',
            'mobile' => $user['mobile'] ?? '',
            'short_dial' => $user['short_dial'] ?? '',
            'address' => $user['address'] ?? '',
            'postal_code' => $user['postal_code'] ?? '',
            'city' => $user['city'] ?? '',
            'country' => $user['country'] ?? '',
            'region' => $user['region'] ?? '',
            'hire_date' => $user['hire_date'] ?? '',
            'locale' => $user['locale'] ?? '',
            'theme' => $user['theme'] ?? '',
            'email_verified_at' => $user['email_verified_at'] ?? '',
            'last_login_at' => $user['last_login_at'] ?? '',
            'last_login_provider' => $user['last_login_provider'] ?? '',
            'active' => (bool) ($user['active'] ?? 1),
            'created' => $user['created'] ?? '',
            'modified' => $user['modified'] ?? '',
            'current_tenant' => $currentTenant,
            'primary_tenant' => $primaryTenant,
            'permissions' => $publicPermissions,
            'assignments' => $publicAssignments,
            'custom_fields' => $publicCustomFields,
        ],
    ]);
}

if ($method === 'PUT' || $method === 'PATCH') {
    $user = $userAccountService->findByUuid($uuid);
    $userId = (int) ($user['id'] ?? 0);

    $input = $request->bodyAll();
    $normalizeResult = app(UserApiWriteInputMapper::class)->normalize($input);
    if ($normalizeResult['ok'] !== true) {
        $errors = $normalizeResult['errors'] ?? [];
        ApiResponse::validationFromFormErrors(formErrorsFrom($errors ?: ['input' => ['invalid_value']]));
    }
    $input = $normalizeResult['input'] ?? $input;

    $decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_UPDATE, [
        'actor_user_id' => ApiAuth::userId(),
        'target_user_id' => $userId,
        'scoped_tenant_id' => ApiAuth::scopedTenantId(),
        'input' => $input,
    ]);
    $apiDeny($decision);
    if (!$user) {
        ApiResponse::notFound();
    }

    $authorizedInput = $decision->attribute('input', null);
    if (is_array($authorizedInput)) {
        $input = $authorizedInput;
    }
    $result = $userAccountService->updateFromAdmin($userId, $input, ApiAuth::userId());
    ApiResponse::fromServiceResult($result);
}

if ($method === 'DELETE') {
    $user = $userAccountService->findByUuid($uuid);
    $userId = (int) ($user['id'] ?? 0);
    $decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_SHOW_DELETE, [
        'actor_user_id' => ApiAuth::userId(),
        'target_user_id' => $userId,
        'scoped_tenant_id' => ApiAuth::scopedTenantId(),
    ]);
    $apiDeny($decision);
    if (!$user) {
        ApiResponse::notFound();
    }

    $result = $userAccountService->deleteByUuid($uuid, ApiAuth::userId());
    ApiResponse::fromServiceResult($result);
}

ApiResponse::methodNotAllowed();
