<?php

use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Session;
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);

if ((requestInput()->method()) !== 'POST') {
    Router::redirect('admin/users');
    return;
}

$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
    if (Request::wantsJson()) {
        http_response_code(400);
        Router::json(['error' => 'csrf']);
        return;
    }
    $errorBag->addGlobal(t('Form expired, please try again'));
    flashFormErrors($errorBag, 'admin/users', 'user_activate');
    Router::redirect('admin/users');
    return;
}

$uuid = trim((string) ($id ?? ''));
$currentUserId = (int) ($session['user']['id'] ?? 0);
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
$userId = (int) ($user['id'] ?? 0);
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_ACTIVATE, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!$decision->isAllowed()) {
    if (Request::wantsJson()) {
        http_response_code($decision->status());
        Router::json(['error' => $decision->error()]);
        return;
    }
    Router::redirect('error/forbidden?url=' . urlencode(Request::pathWithQuery()));
    return;
}
$result = $userAccountService->setActiveByUuid($uuid, true, $currentUserId);
if ($result['ok'] ?? false) {
    if (Request::wantsJson()) {
        http_response_code(204);
        return;
    }
} elseif (Request::wantsJson()) {
    http_response_code((int) ($result['status'] ?? 404));
    Router::json(['error' => 'not_found']);
    return;
} else {
    $errorBag->addGlobal(t('User not found'));
    flashFormErrors($errorBag, 'admin/users', 'user_activate');
}

Router::redirect('admin/users');
