<?php

declare(strict_types=1);

/**
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 *
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 *
 * Copy of the Licence is available at:
 * https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Licence is distributed on an as is basis,
 * without warranties or conditions of any kind, either express or implied.
 * Check the Licence for the specific language governing permissions
 * and limitations under the License.
 *
 * @author   Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

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

/**
 * 8.1.0 — RSA request auth + inbound-webhook HMAC (clean RSA-only). Provisions the webhook
 * idempotency table; the RSA key pair registers itself zero-touch via the cron / back-office
 * backstop once the merchant API key is present.
 *
 * @param \Simplyin $module
 */
function upgrade_module_8_1_0($module)
{
    // SIN-1584: hard-block an in-place upgrade from the legacy PrestaShop 1.7 line. Both lines
    // ship as the "simplyin" module (same dir), so uploading this PS8/9 zip over the old 1.7
    // module is treated by PrestaShop as an in-place upgrade — but the 1.7 line uses 1.6/1.7-era
    // APIs/schema that are incompatible here, and a dirty in-place upgrade breaks the checkout.
    // Discriminator: the 1.7 line ships versions in the 3.x–4.x range while the PS8/9 line never
    // had 3.x–7.x, so a database (from) version in [3.0.0, 8.0.0) unambiguously means the old
    // module is being upgraded in place. Refuse the upgrade and persist a flag so the back office
    // keeps warning until the merchant uninstalls the old module cleanly. (2.x is intentionally
    // NOT caught — both lines historically shipped 2.x, so blocking it would false-positive on
    // legitimate PS8/9 upgrades.)
    $fromVersion = (string) $module->database_version;
    if ($fromVersion !== ''
        && \Tools::version_compare($fromVersion, '3.0.0', '>=')
        && \Tools::version_compare($fromVersion, '8.0.0', '<')) {
        \Configuration::updateValue('SIMPLYIN_LEGACY_CONFLICT', $fromVersion);

        return false;
    }

    \Configuration::deleteByName('SIMPLYIN_LEGACY_CONFLICT');

    return \SimplyIn\Webhook\WebhookDeduplicator::installSql();
}
