<?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\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,
    ) {
    }

    /**
     * @return array<int, object>
     */
    public function getAvailableMethods(): array
    {
        $authToken = (string) $this->session->get('simplyin_auth_token', '');
        $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);

            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;
    }
}
