<?php

use MintyPHP\Module\Audit\AuditAuthorizationPolicy;
use MintyPHP\Module\Audit\Service\SystemAuditRowPresenter;
use MintyPHP\Module\Audit\Service\SystemAuditService;
use MintyPHP\Service\Export\ExportColumn;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(AuditAuthorizationPolicy::ABILITY_SYSTEM_AUDIT_VIEW);
exportRequireGetRequest();

$request = requestInput();

$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');
$filters['limit'] = exportCapLimit($request->query('limit'), 5000);
$filters['offset'] = 0;

$result = app(SystemAuditService::class)->listPaged($filters);
$rows = app(SystemAuditRowPresenter::class)->presentAll((array) ($result['rows'] ?? []));

$columns = [
    new ExportColumn(t('ID'),           static fn (array $r): string => (string) ($r['id'] ?? '')),
    new ExportColumn(t('Created'),      static fn (array $r): string => (string) ($r['created_at'] ?? '')),
    new ExportColumn(t('Event'),        static fn (array $r): string => (string) ($r['event_type'] ?? '')),
    new ExportColumn(t('Status'),       static fn (array $r): string => (string) ($r['outcome_label'] ?? '')),
    new ExportColumn(t('Channel'),      static fn (array $r): string => (string) ($r['channel_label'] ?? '')),
    new ExportColumn(t('Actor'),        static fn (array $r): string => (string) ($r['actor_user_label'] ?? '')),
    new ExportColumn(t('Actor email'),  static fn (array $r): string => (string) ($r['actor_user_email'] ?? '')),
    new ExportColumn(t('Target type'),  static fn (array $r): string => (string) ($r['target_type'] ?? '')),
    new ExportColumn(t('Target UUID'),  static fn (array $r): string => (string) ($r['target_uuid'] ?? '')),
    new ExportColumn(t('Request ID'),   static fn (array $r): string => (string) ($r['request_id'] ?? '')),
    new ExportColumn(t('Error code'),   static fn (array $r): string => (string) ($r['error_code'] ?? '')),
];

$filename = 'system-audit-' . date('Ymd-His') . '.csv';

exportSendCsv($filename, $rows, $columns, exportResolveFlavor($request));
