<?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: simplyinCheckPushStatus mutation
 */
class CheckPushStatus 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'] ?? '');
        $notificationTokenId = trim($args['notification_token_id'] ?? '');

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

        try {
            $response = $this->apiClient->checkPushStatus($email, $notificationTokenId);

            if (!$response['success']) {
                return array_merge(
                    $this->errorOutput($response['error'] ?? 'Failed to check push status'),
                    ['approved' => false]
                );
            }

            $data      = $response['data'] ?? [];
            $approved  = isset($data['ok']) && $data['ok'] === true;
            $authToken = $data['authToken'] ?? null;

            if ($approved && $authToken) {
                $userData = $this->fetchUserData($authToken);

                return [
                    'success'       => true,
                    'message'       => 'Push notification approved',
                    'approved'      => true,
                    'auth_token'    => $authToken,
                    'refresh_token' => $data['refreshToken'] ?? null,
                    'user_data'     => $userData,
                ];
            }

            return [
                'success'  => true,
                'message'  => 'Waiting for approval',
                'approved' => false,
            ];
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GraphQL CheckPushStatus: ' . $e->getMessage());
            return array_merge(
                $this->errorOutput('An unexpected error occurred. Please try again.'),
                ['approved' => false]
            );
        }
    }

    /**
     * Fetch and build user_data output for the given auth token
     *
     * @param string $authToken
     * @return array
     */
    private function fetchUserData(string $authToken): array
    {
        $userData = [];
        $userDataResponse = $this->apiClient->getUserData($authToken);
        if ($userDataResponse['success']) {
            $raw = $userDataResponse['data'];
            if (isset($raw['data'])) {
                $raw = $raw['data'];
            }
            $userData = [
                'raw_json' => json_encode($raw),
                'email'    => $raw['email'] ?? null,
                'name'     => $raw['name'] ?? null,
                'surname'  => $raw['surname'] ?? null,
                'phone'    => $raw['phone'] ?? null,
            ];
        }

        return $userData;
    }
}
