<?php

use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
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 (!actionRequirePost('admin/users')) {
    return;
}

if (!actionRequireCsrf(
    'admin/users',
    'admin/users',
    'user_deactivate',
    jsonAware: true
)) {
    return;
}

$uuid = trim((string) ($id ?? ''));
$currentUserId = (int) ($session['user']['id'] ?? 0);
$user = $uuid !== '' ? $userAccountService->findByUuid($uuid) : null;
$userId = (int) ($user['id'] ?? 0);
$errorBag = formErrors();
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_DEACTIVATE, [
    'actor_user_id' => $currentUserId,
    'target_user_id' => $userId,
]);
if (!actionAllowOrDeny($decision)) {
    return;
}
$result = $userAccountService->setActiveByUuid($uuid, false, $currentUserId);
if (!($result['ok'] ?? false)) {
    if (($result['error'] ?? '') === 'self_deactivate') {
        $errorBag->addGlobal('You cannot deactivate your own account');
        if (Request::wantsJson()) {
            http_response_code(400);
            Router::json(['error' => 'self_deactivate']);
            return;
        }
    } elseif (Request::wantsJson()) {
        http_response_code((int) ($result['status'] ?? 404));
        Router::json(['error' => 'not_found']);
        return;
    }
    flashFormErrors($errorBag, 'admin/users', 'user_deactivate');
    Router::redirect('admin/users');
    return;
}

if (Request::wantsJson()) {
    http_response_code(204);
    return;
}

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