<?php

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

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->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');
}
$redirectTarget = "admin/users/edit/{$uuid}";

$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 (!actionRequirePost($redirectTarget)) {
    return;
}

if (!actionRequireCsrf($redirectTarget, $redirectTarget, 'csrf_expired')) {
    return;
}

$name = trim((string) (requestInput()->bodyAll()['token_name'] ?? ''));

if ($name === '') {
    Flash::error(t('Token name is required'), $redirectTarget, 'api_token_error');
    Router::redirect($redirectTarget);
}

$result = $apiTokenService->create($userId, $name, null, null, $currentUserId);

if ($result['ok'] ?? false) {
    $sessionStore->set('api_token_created', ['token' => $result['token'], 'uuid' => $uuid]);
    Flash::success(t('API token created. Copy it now — it will not be shown again.'), $redirectTarget, 'api_token_created');
} else {
    $error = $result['error'] ?? 'create_failed';
    Flash::error(t('Could not create API token: %s', $error), $redirectTarget, 'api_token_error');
}

Router::redirect($redirectTarget);
