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

/**
 * Resolver: simplyinGetUserData query
 */
class GetUserData 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
    {
        $authToken = trim($args['auth_token'] ?? '');
        if (empty($authToken)) {
            throw new GraphQlInputException(__('auth_token is required.'));
        }

        try {
            $response = $this->apiClient->getUserData($authToken);

            if ($response['success']) {
                $raw = $response['data'];
                if (isset($raw['data'])) {
                    $raw = $raw['data'];
                }

                return [
                    'success'   => true,
                    'message'   => 'User data retrieved successfully',
                    'user_data' => [
                        'raw_json' => json_encode($raw),
                        'email'    => $raw['email'] ?? null,
                        'name'     => $raw['name'] ?? null,
                        'surname'  => $raw['surname'] ?? null,
                        'phone'    => $raw['phone'] ?? null,
                    ],
                ];
            }

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