<?php

namespace MintyPHP\Module\Audit\Support;

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

final class AuditPageHelper
{
    /**
     * Guard a purge action: require login, ability, POST method, and valid CSRF token.
     * Redirects on any failure (never returns in that case).
     */
    public static function requirePurgePost(string $ability, string $route, string $flashGroup): void
    {
        Guard::requireLogin();
        Guard::requireAbility($ability);

        if (strtoupper((string) requestInput()->method()) !== 'POST') {
            Router::redirect($route);
        }

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

    /**
     * Guard a view action: require login + ability, find record by ID, redirect on not-found.
     *
     * @return array<string, mixed> The found record
     */
    public static function findOrRedirect(
        string $ability,
        string $serviceClass,
        string $route,
        string $errorMessage,
        string $flashGroup,
        string $title,
        mixed $id = null
    ): array {
        Guard::requireLogin();
        Guard::requireAbility($ability);

        $recordId = (int) ($id ?? 0);
        $record = $recordId > 0 ? app($serviceClass)->find($recordId) : null;
        if (!$record) {
            Flash::error(t($errorMessage), $route, $flashGroup);
            Router::redirect($route);
        }

        Buffer::set('title', t($title));

        return $record;
    }
}
