<?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 Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Resolver: simplyinVerifyPayment mutation
 */
class VerifyPayment extends AbstractResolver
{
    /**
     * @var ApiClient
     */
    private ApiClient $apiClient;

    /**
     * @var OrderRepositoryInterface
     */
    private OrderRepositoryInterface $orderRepository;

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

    /**
     * @inheritdoc
     */
    public function resolve(Field $field, $context, ResolveInfo $info, ?array $value = null, ?array $args = null): array
    {
        $magentoOrderId  = (int)($args['magento_order_id'] ?? 0);
        $simplyinOrderId = trim($args['simplyin_order_id'] ?? '');
        $authToken       = $args['auth_token'] ?? '';
        $paymentDataJson = $args['payment_data_json'] ?? '{}';

        if (!$magentoOrderId || empty($simplyinOrderId)) {
            throw new GraphQlInputException(__('magento_order_id and simplyin_order_id are required.'));
        }

        try {
            $order = $this->orderRepository->get($magentoOrderId);

            if (!$order->getId()) {
                return $this->errorOutput('Magento order not found');
            }

            if ($order->getPayment()->getMethod() !== 'simplyin_payment') {
                return $this->errorOutput('Order does not use SimplyIN payment method');
            }

            $paymentData = json_decode($paymentDataJson, true) ?? [];
            $response    = $this->apiClient->createPaymentLink($paymentData, $authToken ?: null);

            if ($response['success']) {
                $data    = $response['data'];
                $payment = $order->getPayment();
                $payment->setAdditionalInformation('simplyin_payment_id', $data['paymentId'] ?? '');
                $payment->setAdditionalInformation('simplyin_provider_payment_id', $data['providerPaymentId'] ?? '');
                $payment->setAdditionalInformation('simplyin_payment_status', $data['status'] ?? 'PENDING');
                $payment->setAdditionalInformation('simplyin_redirect_url', $data['redirectUrl'] ?? '');
                $this->orderRepository->save($order);

                return [
                    'success'          => true,
                    'message'          => 'Payment verification initiated successfully',
                    'payment_raw_json' => json_encode($data),
                ];
            }

            return $this->errorOutput($response['error'] ?? 'Payment verification failed');
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GraphQL VerifyPayment: ' . $e->getMessage());
            return $this->errorOutput('An unexpected error occurred. Please try again.');
        }
    }
}
