<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;

/**
 * Resolver: simplyinUpdateOrderPayment mutation
 */
class UpdateOrderPayment extends AbstractResolver
{
    /**
     * @var OrderRepositoryInterface
     */
    private OrderRepositoryInterface $orderRepository;

    /**
     * @param OrderRepositoryInterface $orderRepository
     * @param LoggerInterface $logger
     */
    public function __construct(OrderRepositoryInterface $orderRepository, LoggerInterface $logger)
    {
        parent::__construct($logger);
        $this->orderRepository = $orderRepository;
    }

    /**
     * @inheritdoc
     */
    public function resolve(Field $field, $context, ResolveInfo $info, ?array $value = null, ?array $args = null): array
    {
        $orderId = (int)($args['order_id'] ?? 0);
        if (!$orderId) {
            throw new GraphQlInputException(__('order_id is required.'));
        }

        try {
            $order   = $this->orderRepository->get($orderId);
            $payment = $order->getPayment();

            if (!$payment) {
                return $this->errorOutput('No payment found for order');
            }

            $simplyinOrderId = $args['simplyin_order_id'] ?? '';
            $paymentInfo     = $args['payment_info'] ?? [];

            if ($simplyinOrderId) {
                $payment->setAdditionalInformation('simplyin_order_id', $simplyinOrderId);
            }

            $this->applyPaymentInfo($payment, $paymentInfo, $simplyinOrderId);

            $this->orderRepository->save($order);

            return ['success' => true, 'message' => 'Order payment info updated successfully'];
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GraphQL UpdateOrderPayment: ' . $e->getMessage());
            return $this->errorOutput('An unexpected error occurred. Please try again.');
        }
    }

    /**
     * Map and apply SimplyIN payment information onto the order payment.
     *
     * @param \Magento\Sales\Api\Data\OrderPaymentInterface $payment
     * @param array $paymentInfo
     * @param string $simplyinOrderId
     * @return void
     */
    private function applyPaymentInfo($payment, array $paymentInfo, string $simplyinOrderId): void
    {
        $infoMap = [
            'simplyin_payment_id'            => 'simplyin_payment_id',
            'simplyin_payment_status'        => 'simplyin_payment_status',
            'simplyin_provider_payment_id'   => 'simplyin_provider_payment_id',
            'simplyin_redirect_url'          => 'simplyin_redirect_url',
            'simplyin_registered_at'         => 'simplyin_registered_at',
        ];

        foreach ($infoMap as $inputKey => $infoKey) {
            if (!empty($paymentInfo[$inputKey])) {
                $payment->setAdditionalInformation($infoKey, $paymentInfo[$inputKey]);
            }
        }

        if (isset($paymentInfo['simplyin_redirect_iframe_allowed'])) {
            $payment->setAdditionalInformation(
                'simplyin_redirect_iframe_allowed',
                $paymentInfo['simplyin_redirect_iframe_allowed'] ? '1' : '0'
            );
        }

        if (empty($simplyinOrderId)) {
            $payment->setAdditionalInformation('simplyin_payment_only', true);
        }
    }
}
