<?php

use MintyPHP\Domain\Taxonomy\SystemAuditOutcome;
use MintyPHP\Router;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbility(OperationsAuthorizationPolicy::ABILITY_ADMIN_SYSTEM_AUDIT_PURGE);

if (strtoupper((string) requestInput()->method()) !== 'POST') {
    Router::redirect('admin/system-audit');
}

$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
    $errorBag->addGlobal(t('Form expired, please try again'));
    flashFormErrors($errorBag, 'admin/system-audit', 'system_audit');
    Router::redirect('admin/system-audit');
}

$service = app(SystemAuditService::class);
$deleted = $service->purgeExpired();
$service->record('admin.system_audit.purge', SystemAuditOutcome::Success->value, [
    'metadata' => ['deleted_count' => $deleted],
]);

Flash::success(sprintf(t('%d system audit entries purged'), $deleted), 'admin/system-audit', 'system_audit_purged');
Router::redirect('admin/system-audit');
