<?php

declare(strict_types=1);

namespace Gls\GlsPoland\PrestaShop\Installer;

use Psr\Log\LoggerInterface;

final class LoggingInstaller implements InstallerInterface, UninstallerInterface
{
    private $installer;
    private $logger;

    private $reset = false;

    public function __construct(InstallerInterface $installer, LoggerInterface $logger)
    {
        $this->installer = $installer;
        $this->logger = $logger;
    }

    public function install(\Module $module): void
    {
        try {
            $this->installer->install($module);

            $this->logger->notice($this->reset ? 'Successful reset' : 'Successful installation');
        } catch (\Throwable $e) {
            $this->logger->critical($this->reset ? 'Reset failed' : 'Installation failed', [
                'error' => $e,
            ]);

            throw $e;
        } finally {
            $this->reset = false;
        }
    }

    public function uninstall(\Module $module, bool $isReset): void
    {
        if (!$this->installer instanceof UninstallerInterface) {
            return;
        }

        $this->reset = $isReset;

        try {
            $this->installer->uninstall($module, $isReset);
        } catch (\Throwable $e) {
            $this->logger->critical($this->reset ? 'Reset failed' : 'Uninstallation failed', [
                'error' => $e,
            ]);

            throw $e;
        }

        if (!$isReset) {
            $this->logger->notice('Successful uninstallation');
        }
    }
}
