<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Audit\AuditAuthorizationPolicy;
use MintyPHP\Module\Audit\Domain\UserLifecycleAction;
use MintyPHP\Module\Audit\Service\UserLifecycleAuditService;
use MintyPHP\Service\Access\UiAccessService;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbilityOrForbidden(AuditAuthorizationPolicy::ABILITY_USER_LIFECYCLE_VIEW);

$auditId = (int) ($id ?? 0);
$auditLog = null;
if ($auditId > 0) {
    $auditLog = app(UserLifecycleAuditService::class)->find($auditId);
}
if (!is_array($auditLog)) {
    http_response_code(404);
    return;
}

$auditService = app(UserLifecycleAuditService::class);
$snapshot = null;
if ((string) ($auditLog['action'] ?? '') === UserLifecycleAction::Delete->value) {
    $snapshot = $auditService->decryptSnapshot($auditLog);
}
$viewAuth = is_array($viewAuth ?? null) ? $viewAuth : [];
$viewAuth['page'] = app(UiAccessService::class)->pageCapabilities(
    (int) ($session['user']['id'] ?? 0),
    ['can_restore' => AuditAuthorizationPolicy::ABILITY_USER_LIFECYCLE_RESTORE]
);
