<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
use MintyPHP\Support\Guard;

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

$currentUserId = (int) ($session['user']['id'] ?? 0);
$decision = Guard::requireAbilityDecisionOrForbidden(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_VIEW);
$capabilities = $decision->attribute('capabilities', []);
$tenantIds = is_array($capabilities) ? toIntIds($capabilities['allowed_tenant_ids'] ?? []) : [];

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

$result = app(\MintyPHP\Service\Org\DepartmentService::class)->listPaged([
    'limit' => $filters['limit'],
    'offset' => $filters['offset'],
    'search' => $filters['search'],
    'order' => $filters['order'],
    'dir' => $filters['dir'],
    'tenant' => $filters['tenant'],
    'active' => $filters['active'],
    'tenantIds' => $tenantIds,
    'tenantUserId' => $currentUserId,
]);

$settingsDefaultsGateway = app(\MintyPHP\Service\Settings\SettingsDefaultsGateway::class);
$defaultDepartmentId = $settingsDefaultsGateway->getDefaultDepartmentId();
$userDepartmentRepository = app(\MintyPHP\Repository\Org\UserDepartmentRepository::class);
$userCounts = app(\MintyPHP\Service\Data\GridUserCountEnricher::class)->computeCounts(
    $result['rows'],
    $userDepartmentRepository->countUsersByDepartmentIds(...),
    $userDepartmentRepository->countActiveUsersByDepartmentIds(...)
);

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

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