<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Audit\AuditAuthorizationPolicy;
use MintyPHP\Module\Audit\Service\ApiAuditService;
use MintyPHP\Service\Access\SettingsAuthorizationPolicy;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(AuditAuthorizationPolicy::ABILITY_API_AUDIT_VIEW);
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
    (int) ($session['user']['id'] ?? 0),
    ['can_purge' => SettingsAuthorizationPolicy::ABILITY_ADMIN_SETTINGS_UPDATE]
);

Buffer::set('title', t('API audit logs'));
$breadcrumbs = [
    ['label' => t('Home'), 'path' => 'admin'],
    ['label' => t('API audit logs')],
];
Buffer::set('grid_lang', json_encode(gridLang(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

$filterSchema = require __DIR__ . '/filter-schema.php';
$filterState = gridParseFilters(requestInput()->queryAll(), [
    ...gridSchemaQuery($filterSchema),
    'tenant_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
    'user_ids' => ['type' => 'csv_ids', 'max' => 200, 'return' => 'array'],
]);
$filterOptions = app(ApiAuditService::class)->filterOptions(200);

$activeTenantIds = array_map('strval', is_array($filterState['tenant_ids'] ?? null) ? $filterState['tenant_ids'] : []);
$activeUserIds = array_map('strval', is_array($filterState['user_ids'] ?? null) ? $filterState['user_ids'] : []);

$apiAuditTenantItems = [];
foreach ((array) ($filterOptions['tenants'] ?? []) as $tenantOption) {
    if (!is_array($tenantOption)) {
        continue;
    }
    $tenantId = (int) ($tenantOption['id'] ?? 0);
    if ($tenantId <= 0) {
        continue;
    }
    $tenantLabel = trim((string) ($tenantOption['description'] ?? ''));
    $tenantExists = (bool) ($tenantOption['exists'] ?? false);
    if ($tenantLabel === '') {
        $tenantLabel = $tenantExists
            ? sprintf(t('Tenant #%d'), $tenantId)
            : sprintf(t('Tenant #%d (deleted)'), $tenantId);
    }

    $id = (string) $tenantId;
    $apiAuditTenantItems[$id] = [
        'id' => $id,
        'description' => $tenantLabel,
    ];
}
foreach ($activeTenantIds as $tenantId) {
    if (!isset($apiAuditTenantItems[$tenantId])) {
        $apiAuditTenantItems[$tenantId] = [
            'id' => $tenantId,
            'description' => sprintf(t('Tenant #%d (deleted)'), (int) $tenantId),
        ];
    }
}
$apiAuditTenantItems = array_values($apiAuditTenantItems);

$apiAuditUserItems = [];
foreach ((array) ($filterOptions['users'] ?? []) as $userOption) {
    if (!is_array($userOption)) {
        continue;
    }
    $userId = (int) ($userOption['id'] ?? 0);
    if ($userId <= 0) {
        continue;
    }
    $userDisplayName = trim((string) ($userOption['display_name'] ?? ''));
    $userEmail = trim((string) ($userOption['email'] ?? ''));
    $userExists = (bool) ($userOption['exists'] ?? false);
    $userLabel = $userDisplayName !== '' ? $userDisplayName : $userEmail;
    if ($userLabel === '') {
        $userLabel = $userExists
            ? sprintf(t('User #%d'), $userId)
            : sprintf(t('User #%d (deleted)'), $userId);
    }

    $id = (string) $userId;
    $apiAuditUserItems[$id] = [
        'id' => $id,
        'description' => $userLabel,
    ];
}
foreach ($activeUserIds as $userId) {
    if (!isset($apiAuditUserItems[$userId])) {
        $apiAuditUserItems[$userId] = [
            'id' => $userId,
            'description' => sprintf(t('User #%d (deleted)'), (int) $userId),
        ];
    }
}
$apiAuditUserItems = array_values($apiAuditUserItems);

$toolbarFilterState = [
    'search' => (string) ($filterState['search'] ?? ''),
    'status' => (string) ($filterState['status'] ?? ''),
    'method' => (string) ($filterState['method'] ?? ''),
    'created_from' => (string) ($filterState['created_from'] ?? ''),
    'created_to' => (string) ($filterState['created_to'] ?? ''),
    'tenant_ids' => $activeTenantIds,
    'user_ids' => $activeUserIds,
];
$toolbarOptionSets = [
    'tenant_items' => $apiAuditTenantItems,
    'user_items' => $apiAuditUserItems,
];
$listFilterContext = gridBuildListFilterContext($filterSchema, [
    'filter_state' => $filterState,
    'search_keys' => ['search'],
    'toolbar_state_overrides' => $toolbarFilterState,
    'toolbar_option_sets' => $toolbarOptionSets,
]);
$toolbarFilterSchema = $listFilterContext['toolbarFilterSchema'];
$toolbarFilterState = $listFilterContext['toolbarFilterState'];
$searchToolbarFilterSchema = $listFilterContext['searchToolbarFilterSchema'];
$drawerToolbarFilterSchema = $listFilterContext['drawerToolbarFilterSchema'];
$schemaByKey = $listFilterContext['schemaByKey'];
$toolbarOptionSets = $listFilterContext['toolbarOptionSets'];
$filterChipMeta = [
    'search' => [
        'label' => t('Search'),
        'type' => 'text',
    ],
    'status' => [
        'label' => t('Status'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['status']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['status'] ?? [])),
    ],
    'method' => [
        'label' => t('Method'),
        'type' => 'select',
        'default' => (string) (($schemaByKey['method']['default'] ?? '')),
        'options' => gridOptionMapFromAllowed((array) ($schemaByKey['method'] ?? [])),
    ],
    'tenant_ids' => [
        'label' => t('Tenants'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($apiAuditTenantItems),
    ],
    'user_ids' => [
        'label' => t('Users'),
        'type' => 'multi_csv',
        'options' => gridOptionMapFromItems($apiAuditUserItems),
    ],
    'created_range' => [
        'label' => t('Created'),
        'type' => 'date_range',
        'from_param' => 'created_from',
        'to_param' => 'created_to',
    ],
];
$clientFilterSchema = $listFilterContext['clientFilterSchema'];
$searchConfig = $listFilterContext['searchConfig'];
