<?php

declare(strict_types=1);

namespace apexl\Io\modules\display\hooks;

use apexl\Io\includes\Entity;
use apexl\Io\includes\RouteManager;
use apexl\Io\interfaces\AbstractHook;
use apexl\Io\services\Output;

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

    public function __invoke(array $response, string $route, Output $output, RouteManager $routeManager): void
    {
        if (strpos($route, 'Entity.delete')) {
            $entity = $output->getMetadata('core.controller.delete.entityType')['entityType'] ?? false;
            $entityId = $output->getMetadata('core.controller.delete.entityId')['entityId'] ?? false;

            if ($entity && $entityId) {
                /** @var Entity $instantEntity */
                $instantEntity = new $entity();
                $output->addMetadata(
                    sprintf('%s.delete.redirect', $instantEntity->getEntityName()),
                    'redirect',
                    $routeManager->getRoutePattern(
                        sprintf('%s.display.all', $instantEntity->getEntityName())
                    )
                );
            }
        }
    }
}
