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

/**
 * Resolver: simplyinCheckEmail mutation
 */
class CheckEmail 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
    {
        $email = trim($args['email'] ?? '');
        if (empty($email)) {
            throw new GraphQlInputException(__('email is required.'));
        }

        try {
            $response = $this->apiClient->submitEmail($email);

            if ($response['success']) {
                $data = $response['data'] ?? [];
                return [
                    'success'                      => true,
                    'message'                      => 'OTP sent successfully',
                    'user_exists'                  => true,
                    'user_used_push_notifications' => (bool)($data['userUsedPushNotifications'] ?? false),
                    'notification_token_id'        => $data['notificationTokenId'] ?? null,
                    'code'                         => $data['code'] ?? null,
                    'masked_data'                  => isset($data['data']) ? json_encode($data['data']) : null,
                ];
            }

            if (($response['error'] ?? '') === 'USER_NOT_FOUND') {
                return [
                    'success'     => true,
                    'message'     => 'User not found',
                    'user_exists' => false,
                ];
            }

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