<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Installer;

use Gls\GlsPoland\PrestaShop\Message\CreateAdminTabCommand;
use Gls\GlsPoland\Translation\TranslatorAwareTrait;
use PrestaShop\PrestaShop\Core\CommandBus\CommandBusInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Adds admin tabs that were skipped by @see ModuleTabManagementSubscriber due to missing legacy admin controller class.
 * Tab removal can be handled by @see ModuleTabManagementSubscriber
 */
final class TabInstaller implements InstallerInterface
{
    use TranslatorAwareTrait;

    private $bus;
    private $denormalizer;
    private $psVersion;

    public function __construct(CommandBusInterface $bus, DenormalizerInterface $denormalizer, string $psVersion)
    {
        $this->bus = $bus;
        $this->denormalizer = $denormalizer;
        $this->psVersion = $psVersion;
    }

    public function install(\Module $module): void
    {
        foreach ($module->getTabs() as $tabDetails) {
            $this->installTab($module, $tabDetails);
        }
    }

    private function installTab(\Module $module, array $tabDetails): void
    {
        if (null === ($tabDetails['route_name'] ?? null) || \Tools::version_compare($this->psVersion, '1.7.7', '>=')) {
            return;
        }

        $tabDetails['module_name'] = $module->name;
        /** @var CreateAdminTabCommand $command */
        $command = $this->denormalizer->denormalize($tabDetails, CreateAdminTabCommand::class);

        try {
            $this->bus->handle($command);
        } catch (\Exception $e) {
            throw new InstallerException($this->getTranslator()->trans('Failed to install admin tab "%name%".', ['%name%' => $command->getClassName()], 'Admin.Modules.Notification'), 0, $e);
        }
    }
}
