<?php

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

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();

$user = $session['user'] ?? [];
$userId = (int) ($user['id'] ?? 0);
$uuid = trim((string) ($user['uuid'] ?? ''));
if ($uuid === '') {
    Router::redirect('login');
}

$decision = app(AuthorizationService::class)->authorize(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_EDIT_CONTEXT, [
    'actor_user_id' => $userId,
    'target_user_id' => $userId,
]);
$capabilities = $decision->attribute('capabilities', []);
$canViewPage = is_array($capabilities) && (bool) ($capabilities['can_view_page'] ?? false);
if (!$decision->isAllowed() || !$canViewPage) {
    Router::redirect('error/forbidden');
}

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