<?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: simplyinResendOtp mutation
 */
class ResendOtp 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'] ?? '');
        $method = $args['method'] ?? 'sms';

        if (empty($email)) {
            throw new GraphQlInputException(__('email is required.'));
        }

        try {
            $response = $method === 'email'
                ? $this->apiClient->resendOtpViaEmail($email)
                : $this->apiClient->resendOtpViaSms($email);

            if ($response['success']) {
                return [
                    'success' => true,
                    'message' => 'OTP resent to your ' . ($method === 'email' ? 'email' : 'SMS'),
                    'method'  => $method,
                ];
            }

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