<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Hook;

use PrestaShop\PrestaShop\Core\Module\Exception\ModuleErrorInterface;
use Psr\Log\LoggerInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class ErrorHandlingHookDispatcher implements HookDispatcherInterface
{
    /**
     * @var HookDispatcherInterface
     */
    private $dispatcher;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var bool
     */
    private $debug;

    public function __construct(HookDispatcherInterface $dispatcher, LoggerInterface $logger, bool $debug = false)
    {
        $this->dispatcher = $dispatcher;
        $this->logger = $logger;
        $this->debug = $debug;
    }

    /**
     * {@inheritDoc}
     */
    public function dispatch(string $name, array $parameters)
    {
        try {
            return $this->dispatcher->dispatch($name, $parameters);
        } catch (\Throwable $e) {
            $this->handleError($e, $name);

            return null;
        }
    }

    private function handleError(\Throwable $e, string $hookName): void
    {
        if ($e instanceof ModuleErrorInterface) {
            throw $e;
        }

        $this->logger->critical('Error executing hook "{hookName}": {exception}', [
            'hookName' => $hookName,
            'exception' => $e,
        ]);

        if ($this->debug) {
            throw $e;
        }
    }
}
