<?php

use MintyPHP\Http\Request;
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);

if ((requestInput()->method()) !== 'POST') {
    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);
$errorBag = formErrors();
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_DELETE, [
    '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->deleteByUuid($uuid, $currentUserId);

if (!($result['ok'] ?? false)) {
    if (($result['error'] ?? '') === 'self_delete') {
        $errorBag->addGlobal('You cannot delete your own account');
        if (Request::wantsJson()) {
            http_response_code(400);
            Router::json(['error' => 'self_delete']);
            return;
        }
    } else {
        $errorBag->addGlobal('User not found');
        if (Request::wantsJson()) {
            http_response_code(404);
            Router::json(['error' => 'not_found']);
            return;
        }
    }
    flashFormErrors($errorBag, 'admin/users', 'user_delete');
    Router::redirect('admin/users');
    return;
}

if (Request::wantsJson()) {
    http_response_code(204);
    Router::json([]);
    return;
}

Flash::success('User deleted', 'admin/users', 'user_deleted');
Router::redirect('admin/users');
