<?php

use MintyPHP\Domain\Taxonomy\UserLifecycleAction;
use MintyPHP\Domain\Taxonomy\UserLifecycleStatus;
use MintyPHP\Domain\Taxonomy\UserLifecycleTriggerType;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(OperationsAuthorizationPolicy::ABILITY_ADMIN_USER_LIFECYCLE_AUDIT_VIEW);
gridRequireGetRequest();

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

$result = app(\MintyPHP\Service\Audit\UserLifecycleAuditService::class)->listPaged($filters);

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $status = UserLifecycleStatus::normalizeOr((string) ($row['status'] ?? ''), UserLifecycleStatus::Failed);
    $action = UserLifecycleAction::normalizeOr((string) ($row['action'] ?? ''), UserLifecycleAction::Deactivate);
    $triggerType = UserLifecycleTriggerType::normalizeOr((string) ($row['trigger_type'] ?? ''), UserLifecycleTriggerType::System);

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'created_at' => dt((string) ($row['created_at'] ?? '')),
        'status' => $status->value,
        'status_badge' => $status->badgeVariant(),
        'status_label' => t($status->labelToken()),
        'action' => $action->value,
        'action_label' => t($action->labelToken()),
        'trigger_type' => $triggerType->value,
        'trigger_type_label' => t($triggerType->labelToken()),
        'reason_code' => (string) ($row['reason_code'] ?? ''),
        'target_user_uuid' => (string) ($row['target_user_uuid'] ?? ''),
        'target_user_email' => (string) ($row['target_user_email'] ?? ''),
        'restored_at' => dt((string) ($row['restored_at'] ?? '')),
    ];
}

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