<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Installer;

use Gls\GlsPoland\PrestaShop\ObjectModel\Persistence;
use Gls\GlsPoland\PrestaShop\ObjectModel\PersistenceInterface;
use Gls\GlsPoland\Translation\TranslatorAwareTrait;

final class HookInstaller implements InstallerInterface
{
    use TranslatorAwareTrait;

    private $hooksProvider;
    private $persistence;

    public function __construct(AvailableHooksProviderInterface $hooksProvider, ?PersistenceInterface $persistence = null)
    {
        $this->hooksProvider = $hooksProvider;
        $this->persistence = $persistence ?? new Persistence();
    }

    public function install(\Module $module): void
    {
        $hookNames = $this->hooksProvider->getAvailableHooks();

        try {
            $result = $this->persistence->execute(static function () use ($module, $hookNames): bool {
                return (bool) $module->registerHook($hookNames);
            });
        } catch (\Exception $e) {
            throw new InstallerException($this->getTranslator()->trans('Could not register hooks.', [], 'Modules.Glspoland.Installer'), 0, $e);
        }

        if (!$result) {
            throw new InstallerException($this->getTranslator()->trans('Could not register hooks.', [], 'Modules.Glspoland.Installer'));
        }
    }
}
