<?php

/**
 * Resolve the profile target for the current session user.
 */
function accountUrl(): string
{
    $user = $_SESSION['user'] ?? [];
    $uuid = (string) ($user['uuid'] ?? '');
    return $uuid !== '' ? lurl('profile') : lurl('login');
}

/**
 * Check if the current user has a permission key.
 */
function can(string $permissionKey): bool
{
    $userId = (int) ($_SESSION['user']['id'] ?? 0);
    if ($userId <= 0) {
        return false;
    }
    if (!function_exists('permissionGateway')) {
        return false;
    }

    $permissionGateway = permissionGateway();

    // First try the in-memory/session cache, then fall back to a direct fetch.
    $keys = $permissionGateway->getCachedPermissions($userId);
    if (!$keys) {
        $keys = $permissionGateway->getUserPermissions($userId);
        if (!$keys) {
            return false;
        }
    }
    return in_array($permissionKey, $keys, true);
}
