<?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: simplyinCreateAccount mutation
 */
class CreateAccount 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'] ?? '');
        $firstName = trim($args['first_name'] ?? '');
        $lastName  = trim($args['last_name'] ?? '');
        $phone     = trim($args['phone'] ?? '');

        if (empty($email) || empty($firstName) || empty($lastName) || empty($phone)) {
            throw new GraphQlInputException(__('email, first_name, last_name and phone are required.'));
        }

        try {
            $response = $this->apiClient->createAccount($email, $firstName, $lastName, $phone);

            if ($response['success']) {
                return [
                    'success'      => true,
                    'message'      => $response['message'] ?? 'Account created successfully',
                    'auth_token'   => $response['data']['authToken'] ?? null,
                    'requires_otp' => (bool)($response['requiresOtp'] ?? false),
                ];
            }

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