<?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 PrestaShopLogger;
use SimplyIn\Api\ApiException;
use SimplyIn\Api\ConnectionOutcome;
use SimplyIn\Api\SimplyInApiClient;
use SimplyIn\Session\SimplyInSessionInterface;

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

final class PaymentMethodsProvider
{
    private const CACHE_TTL_SECONDS = 120;

    public function __construct(
        private readonly SimplyInApiClient $apiClient,
        private readonly SimplyInSessionInterface $session,
    ) {
    }

    /**
     * @param null|int $idOrder the order a pay-again paywall is being built for, so a session that
     *                          holds no authorization can fall back to the one that order was
     *                          placed with. Omitted (or null) for the checkout's own paywall, which
     *                          has no order yet and must answer from the session alone.
     *
     * @return array<int, object>
     */
    public function getAvailableMethods(?int $idOrder = null): array
    {
        // AuthorizationResolver is the one place this "session wins, else the order it was placed
        // with" rule is stated - shared with PaywallRenderer::canSaveCard() so a change to how an
        // authorization is recognized cannot fix one and leave the other reading a stale rule.
        $sessionHasToken = trim((string) $this->session->get('simplyin_auth_token', '')) !== '';
        $authToken = AuthorizationResolver::resolve($this->session, $idOrder);
        $usingOrderBoundToken = !$sessionHasToken && $authToken !== '';

        $cacheKey = md5($authToken);

        $cached = $this->session->get('simplyin_pm_cache');
        if (
            is_array($cached)
            && ($cached['key'] ?? null) === $cacheKey
            && (time() - (int) ($cached['time'] ?? 0)) < self::CACHE_TTL_SECONDS
            && is_string($cached['body'] ?? null)
        ) {
            $decoded = json_decode($cached['body']);

            return is_array($decoded) ? $decoded : [];
        }

        try {
            $response = $this->apiClient->request(
                'GET',
                'payments/getAvailablePaymentMethods',
                authToken: $authToken !== '' ? $authToken : null,
            );
        } catch (ApiException $e) {
            PrestaShopLogger::addLog('SimplyIn: getAvailablePaymentMethods request failed: ' . $e->getMessage(), 3);

            // An order-bound authorization the backend explicitly rejects (401/403 - expired or
            // revoked) must not cost the shopper the anonymous methods this same endpoint returns
            // for no token at all. Retried once, with no token, so a stale stored authorization
            // degrades to today's anonymous behaviour instead of an empty paywall.
            //
            // Deliberately NOT retried for anything else (timeout, 5xx, malformed response): those
            // are the backend having a transient problem, not this token being wrong, and retrying
            // anonymously would only add a second doomed call while masking what actually failed.
            if ($usingOrderBoundToken && ConnectionOutcome::fromStatusCode($e->statusCode) === ConnectionOutcome::AUTH_REJECTED) {
                return $this->getAvailableMethods(null);
            }

            return [];
        }

        if ($response->rawBody === null || $response->rawBody === '') {
            return [];
        }
        $decoded = json_decode($response->rawBody);
        if (!is_array($decoded)) {
            return [];
        }

        $this->session->set('simplyin_pm_cache', [
            'key' => $cacheKey,
            'time' => time(),
            'body' => $response->rawBody,
        ]);

        return $decoded;
    }
}
