<?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: simplyinVerifyOtp mutation
 */
class VerifyOtp 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'] ?? '');
        $code  = trim($args['code'] ?? '');

        if (empty($email) || empty($code)) {
            throw new GraphQlInputException(__('email and code are required.'));
        }

        try {
            $response = $this->apiClient->verifyOtp($email, $code);

            if ($response['success'] && isset($response['data']['authToken'])) {
                $authToken = $response['data']['authToken'];

                // Fetch full user data
                $userData = [];
                $userDataResponse = $this->apiClient->getUserData($authToken);
                if ($userDataResponse['success']) {
                    $raw = $userDataResponse['data'];
                    if (isset($raw['data'])) {
                        $raw = $raw['data'];
                    }
                    $userData = $this->buildUserData($raw);
                }

                return [
                    'success'    => true,
                    'message'    => 'OTP verified successfully',
                    'auth_token' => $authToken,
                    'user_data'  => $userData,
                ];
            }

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

    /**
     * Build user_data output from raw API response
     *
     * @param array $raw
     * @return array
     */
    private function buildUserData(array $raw): array
    {
        return [
            'raw_json' => json_encode($raw),
            'email'    => $raw['email'] ?? null,
            'name'     => $raw['name'] ?? null,
            'surname'  => $raw['surname'] ?? null,
            'phone'    => $raw['phone'] ?? null,
        ];
    }
}
