<?php

declare(strict_types=1);

namespace apexl\Io\modules\display\hooks;

use apexl\Io\includes\RouteManager;
use apexl\Io\interfaces\AbstractHook;
use apexl\Io\interfaces\OutputManagerInterface;

readonly class redirectFollowingEntityDeleteHook implements AbstractHook
{
    public function hooks(): array
    {
        return [
            OutputManagerInterface::HOOK__ADD_RESPONSE,
        ];
    }

    public function __invoke(array $response, string $route, OutputManagerInterface $output, RouteManager $routeManager): void
    {
        if (!($response['success'] ?? false) || !str_ends_with($route, '.delete')) {
            return;
        }

        $entityName = substr($route, 0, -strlen('.delete'));
        $pattern = $routeManager->getRoutePattern(sprintf('%s.display.all', $entityName));

        if ($pattern !== null) {
            $output->addMetadata(
                sprintf('%s.delete.redirect', $entityName),
                'redirect',
                $pattern
            );
        }
    }
}
