<?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 Module;
use SimplyInPayments;
use Tools;

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

final class PaymentStatusChecker
{
    public function __construct(
        private readonly PaymentStatusReconcilerInterface $reconciler,
    ) {
    }

    /**
     * @return null|array<string, mixed>
     */
    public function check(Module $module): ?array
    {
        $ajaxToken = (string) Tools::getValue('ajax_token');
        $cartToken = (string) Tools::getValue('cart_token');
        $paymentCheckToken = (string) Tools::getValue('payment_check_token');
        $idCart = (int) Tools::getValue('id_cart');

        $tokensOk = $this->tokensValid($module, $ajaxToken, $cartToken, $paymentCheckToken, $idCart);
        $status = SimplyInPayments::getPaymentInfo($idCart);

        if (!$tokensOk) {
            return [
                'status' => 'error',
                'message' => 'Token error',
            ];
        }

        if (!$status) {
            return null;
        }

        if (PaymentStatus::isTerminal((string) $status->status)) {
            return [
                'status' => $status->status,
                'date' => $status->date_upd,
                // '' when none was ever captured for this attempt - the poller shows the generic
                // sentence on that, never a blank or a raw enum value.
                'reject_reason' => (string) ($status->reject_reason ?? ''),
            ];
        }

        // Not terminal: the attempt is still open, whether because the shopper is away completing
        // it or because we never learned its outcome. Ask the payment service, which is the only
        // authority on which of the two it is.
        if (!empty($status->uuid)) {
            $reconciled = $this->reconciler->reconcile((string) $status->uuid, $idCart);
            if ($reconciled !== null) {
                return $reconciled;
            }
        }

        return [
            'status' => $status->status,
            'date' => $status->date_upd,
            // Still open, so there is nothing to report yet either way - '' keeps this response's
            // shape identical to every other branch here, so the poller never has to treat the key
            // as optional on some paths and not others.
            'reject_reason' => '',
        ];
    }

    private function tokensValid(Module $module, string $ajaxToken, string $cartToken, string $paymentCheckToken, int $idCart): bool
    {

        return $ajaxToken === (string) $module->getAjaxToken()
            && $cartToken === (string) $module->getCartToken($idCart)
            && $paymentCheckToken === (string) $module->getPaymentCheckToken($ajaxToken, $cartToken);
    }
}
