<?php

/**
 * 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
 */

declare(strict_types=1);

namespace SimplyIn\Payment;

use SimplyIn\Session\SimplyInSessionInterface;
use SimplyInOrder;

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

/**
 * The one authorization-lookup rule both {@see PaymentMethodsProvider} and {@see PaywallRenderer}
 * must answer identically: the session's own token when it has one - it reflects what THIS request
 * is actually authorized as - else, when an order id is given, the token that order was placed
 * with. A session that outlives the checkout that placed the order (the order-confirmation page's
 * pay-again surface) falls back to the order; the checkout's own paywall, which has no order yet,
 * never gets a fallback to reach for.
 *
 * Answered in one place so a later change to how an authorization is recognized cannot fix one
 * surface and leave the other reading a stale rule - the same reasoning {@see PaywallRenderer}'s own
 * docblock gives for extracting the paywall pipeline itself.
 */
final class AuthorizationResolver
{
    public static function resolve(SimplyInSessionInterface $session, ?int $idOrder): string
    {
        $sessionToken = trim((string) $session->get('simplyin_auth_token', ''));
        if ($sessionToken !== '') {
            return $sessionToken;
        }

        return $idOrder !== null ? trim(SimplyInOrder::getAuthToken($idOrder)) : '';
    }
}
