<?php

use MintyPHP\Service\Access\RoleAuthorizationPolicy;
use MintyPHP\Support\Guard;

Guard::requireLogin();
gridRequireGetRequest();

Guard::requireAbilityOrForbidden(RoleAuthorizationPolicy::ABILITY_ADMIN_ROLES_VIEW);

$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');

$result = app(\MintyPHP\Service\Access\RoleService::class)->listPaged([
    'limit' => $filters['limit'],
    'offset' => $filters['offset'],
    'search' => $filters['search'],
    'order' => $filters['order'],
    'dir' => $filters['dir'],
    'active' => $filters['active'],
]);

$settingsDefaultsGateway = app(\MintyPHP\Service\Settings\SettingsDefaultsGateway::class);
$defaultRoleId = $settingsDefaultsGateway->getDefaultRoleId();
$rolePermissionRepository = app(\MintyPHP\Repository\Access\RolePermissionRepository::class);
$userRoleRepository = app(\MintyPHP\Repository\Access\UserRoleRepository::class);
$userCounts = app(\MintyPHP\Service\Data\GridUserCountEnricher::class)->computeCounts(
    $result['rows'],
    $userRoleRepository->countUsersByRoleIds(...),
    $userRoleRepository->countActiveUsersByRoleIds(...)
);
$rolePermissionCounts = $rolePermissionRepository->countPermissionsByRoleIds(array_keys($userCounts));

$rows = [];
foreach ($result['rows'] as $row) {
    $roleId = (int) ($row['id'] ?? 0);
    $counts = $userCounts[$roleId] ?? ['active_users' => 0, 'inactive_users' => 0];
    $rows[] = [
        'id' => $row['id'] ?? null,
        'uuid' => $row['uuid'] ?? '',
        'is_default' => $roleId > 0 && $defaultRoleId === $roleId,
        'description' => $row['description'] ?? '',
        'code' => $row['code'] ?? '',
        'active' => (int) ($row['active'] ?? 1),
        'active_users' => $counts['active_users'],
        'inactive_users' => $counts['inactive_users'],
        'permission_count' => (int) ($rolePermissionCounts[$roleId] ?? 0),
        'created' => dt($row['created'] ?? ''),
        'modified' => dt($row['modified'] ?? ''),
    ];
}

gridJsonDataResult($rows, (int) ($result['total'] ?? 0));
