<?php
require __DIR__ . '/../bootstrap.php';

use Gestoreasy\Core\Tenant\ConnectionManager;

$tenant = $argv[1] ?? 'default';
$userId = (int)($argv[2] ?? 1);
$pdo = ConnectionManager::forTenant($tenant);

function row($pdo, $sql, $params = []) {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetch();
}

function rows($pdo, $sql, $params = []) {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

$role = row($pdo, 'SELECT * FROM roles WHERE name = ?', ['admin']);
$perm = row($pdo, 'SELECT * FROM permissions WHERE name = ?', ['fiscal.certs.manage']);
$userRoles = rows($pdo, 'SELECT ur.*, r.name FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = ?', [$userId]);
$rolePerms = rows($pdo, 'SELECT rp.*, p.name FROM role_permissions rp JOIN permissions p ON p.id = rp.permission_id WHERE rp.role_id = ?', [$role['id'] ?? -1]);
$effectivePerms = rows($pdo, 'SELECT p.name FROM permissions p JOIN role_permissions rp ON rp.permission_id = p.id JOIN user_roles ur ON ur.role_id = rp.role_id WHERE ur.user_id = ?', [$userId]);

echo "Tenant: $tenant\n";
echo "User ID: $userId\n";
echo "Role(admin): "; var_export($role); echo "\n";
echo "Perm(fiscal.certs.manage): "; var_export($perm); echo "\n";
echo "UserRoles: "; var_export($userRoles); echo "\n";
echo "RolePermissions(admin): "; var_export($rolePerms); echo "\n";
echo "EffectivePermissions(user): "; var_export(array_map(fn($r)=>$r['name'], $effectivePerms)); echo "\n";