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

/**
 * Resolver: simplyinGetPaymentMethods query
 */
class GetPaymentMethods extends AbstractResolver
{
    /**
     * @var ApiClient
     */
    private ApiClient $apiClient;

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

    /**
     * @inheritdoc
     */
    public function resolve(Field $field, $context, ResolveInfo $info, ?array $value = null, ?array $args = null): array
    {
        try {
            $response = $this->apiClient->getPaymentMethods();

            if ($response['success']) {
                $rawMethods = $response['data'] ?? [];
                $methods = [];

                foreach ($rawMethods as $method) {
                    if (!is_array($method)) {
                        continue;
                    }
                    $methods[] = [
                        'payment_method_id' => $method['paymentMethodId'] ?? null,
                        'type'              => $method['type'] ?? null,
                        'name'              => $method['name'] ?? null,
                        'raw_json'          => json_encode($method),
                    ];
                }

                return [
                    'success'         => true,
                    'message'         => 'Payment methods retrieved successfully',
                    'payment_methods' => $methods,
                ];
            }

            return $this->errorOutput($response['error'] ?? 'Failed to get payment methods');
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GraphQL GetPaymentMethods: ' . $e->getMessage());
            return $this->errorOutput('An unexpected error occurred. Please try again.');
        }
    }
}
