<?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;

/**
 * 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 $psVersion;

    public function __construct(CommandBusInterface $bus, string $psVersion)
    {
        $this->bus = $bus;
        $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)) {
            return;
        }

        $command = new CreateAdminTabCommand(
            (string) ($tabDetails['class_name'] ?? ''),
            $tabDetails['parent_class_name'] ?? null,
            $tabDetails['name'] ?? null,
            (bool) ($tabDetails['visible'] ?? true),
            $tabDetails['icon'] ?? null,
            $tabDetails['route_name'] ?? null,
            $module->name
        );

        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);
        }
    }
}
