<?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: simplyinSearchAddress query
 */
class SearchAddress 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'] ?? '');
        $query     = trim($args['query'] ?? '');

        if (empty($authToken) || empty($query)) {
            throw new GraphQlInputException(__('auth_token and query are required.'));
        }

        try {
            $response = $this->apiClient->searchAddress($query, $authToken);

            if ($response['success']) {
                $addresses = $response['data'] ?? [];
                if (isset($addresses['data']) && is_array($addresses['data'])) {
                    $addresses = $addresses['data'];
                }

                return [
                    'success'            => true,
                    'message'            => 'Addresses found',
                    'addresses_raw_json' => json_encode($addresses),
                ];
            }

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