<?php

use Gls\GlsPoland\PrestaShop\Configuration\Adapter\Configuration;
use Gls\GlsPoland\PrestaShop\Hook;
use Gls\GlsPoland\PrestaShop\Installer\DatabaseInstaller;
use Gls\GlsPoland\PrestaShop\Installer\InstallerInterface;
use Gls\GlsPoland\PrestaShop\Installer\Migration\Version1_1_0;

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

/**
 * @internal
 */
class GlsPolandUpdater_1_1_0
{
    /**
     * @var Module
     */
    private $module;

    /**
     * @var InstallerInterface
     */
    private $installer;

    public function __construct(Module $module, InstallerInterface $installer)
    {
        \Tools::clearSf2Cache('prod');

        $this->module = $module;
        $this->installer = $installer;
    }

    public static function create(Module $module): self
    {
        /** @var \Doctrine\DBAL\Connection $connection */
        $connection = $module->get('database_connection');

        return new self($module, new DatabaseInstaller($connection, [
            Version1_1_0::create(),
        ], new Configuration(true)));
    }

    public function upgrade(): bool
    {
        $this->installer->install($this->module);

        return $this->updateHooks();
    }

    private function updateHooks(): bool
    {
        $this->module->unregisterHook(Hook\Front\Checkout\DisplayAfterCarrier::HOOK_NAME);

        return $this->module->registerHook([
            Hook\Common\ActionDispatcherBefore::HOOK_NAME,
            Hook\Front\Checkout\DisplayBeforeBodyClosingTag::HOOK_NAME,
        ]);
    }
}

function upgrade_module_1_1_0(Module $module): bool
{
    return GlsPolandUpdater_1_1_0::create($module)->upgrade();
}
