<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::API_TOKENS_MANAGE);
$userAccountService = (new UserServicesFactory())->createUserAccountService();
$apiTokenService = (new AuthServicesFactory())->createApiTokenService();

$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);
$name = trim((string) ($_POST['token_name'] ?? ''));

if ($name === '') {
    Flash::error(t('Token name is required'), "admin/users/edit/{$uuid}", 'api_token_error');
    Router::redirect("admin/users/edit/{$uuid}");
}

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

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

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