<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
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);
$rememberMeService = app(\MintyPHP\Service\Auth\RememberMeService::class);

$uuid = trim((string) ($id ?? ''));
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
if (!$user) {
    Flash::error(t('User not found'), 'admin/users', 'user_not_found');
    Router::redirect('admin/users');
}

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

$rememberMeService->forgetAllForUser($userId);
Flash::success(t('Login tokens cleared'), "admin/users/edit/{$uuid}", 'tokens_cleared');
Router::redirect("admin/users/edit/{$uuid}");
