<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);
$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$apiTokenService = app(\MintyPHP\Service\Auth\ApiTokenService::class);

$uuid = trim((string) ($id ?? ''));
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
if (!$user) {
    Router::redirect('admin/users');
}

$userId = (int) ($user['id'] ?? 0);
$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_API_TOKENS_MANAGE, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

if (!Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), "admin/users/edit/{$uuid}", 'csrf_expired');
    Router::redirect("admin/users/edit/{$uuid}");
    return;
}

$tokenId = (int) (requestInput()->bodyAll()['token_id'] ?? 0);

if ($tokenId > 0) {
    $apiTokenService->revoke($tokenId);
    Flash::success(t('API token revoked'), "admin/users/edit/{$uuid}", 'api_token_revoked');
}

Router::redirect("admin/users/edit/{$uuid}");
