<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_USERS_LIFECYCLE_RESTORE);

$auditId = (int) ($id ?? 0);
$errorBag = formErrors();

if (strtoupper((string) (requestInput()->method())) !== 'POST') {
    Router::redirect('admin/user-lifecycle-audit');
}
if (!Session::checkCsrfToken()) {
    $errorBag->addGlobal(t('Form expired, please try again'));
    flashFormErrors($errorBag, 'admin/user-lifecycle-audit', 'user_lifecycle_restore');
    Router::redirect('admin/user-lifecycle-audit');
}

$result = app(\MintyPHP\Service\User\UserLifecycleRestoreService::class)->restoreFromLifecycleAudit(
    $auditId,
    (int) ($session['user']['id'] ?? 0)
);

if (!($result['ok'] ?? false)) {
    $error = (string) ($result['error'] ?? 'restore_unexpected_error');
    if ($error === 'restore_email_exists') {
        $errorBag->addGlobal(t('Restore not possible: email already exists'));
    } elseif ($error === 'restore_uuid_exists') {
        $errorBag->addGlobal(t('Restore not possible: uuid already exists'));
    } elseif ($error === 'snapshot_unavailable') {
        $errorBag->addGlobal(t('Lifecycle snapshot unavailable'));
    } elseif ($error === 'audit_event_already_restored') {
        $errorBag->addGlobal(t('Lifecycle event was already restored'));
    } else {
        $errorBag->addGlobal(t('User restore failed'));
    }
    flashFormErrors($errorBag, "admin/user-lifecycle-audit/view/$auditId", 'user_lifecycle_restore');
    Router::redirect("admin/user-lifecycle-audit/view/$auditId");
}

Flash::success(t('User restored'), "admin/user-lifecycle-audit/view/$auditId", 'user_restored');
Router::redirect("admin/user-lifecycle-audit/view/$auditId");
