<?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: simplyinUpdateShippingMethod mutation
 */
class UpdateShippingMethod 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
    {
        $authToken      = trim($args['auth_token'] ?? '');
        $shippingMethod = $args['shipping_method'] ?? [];

        if (empty($authToken) || empty($shippingMethod)) {
            throw new GraphQlInputException(__('auth_token and shipping_method are required.'));
        }

        if (empty($shippingMethod['carrier_code']) || empty($shippingMethod['method_code'])) {
            throw new GraphQlInputException(__('shipping_method.carrier_code and method_code are required.'));
        }

        try {
            $userDataResponse = $this->apiClient->getUserData($authToken);
            if (!$userDataResponse['success']) {
                return $this->errorOutput('Failed to get user data');
            }

            $userData = $userDataResponse['data'];
            if (isset($userData['data'])) {
                $userData = $userData['data'];
            }

            $userData['selectedShippingMethod'] = [
                'carrier_code'  => $shippingMethod['carrier_code'],
                'method_code'   => $shippingMethod['method_code'],
                'carrier_title' => $shippingMethod['carrier_title'] ?? '',
                'method_title'  => $shippingMethod['method_title'] ?? '',
                'amount'        => $shippingMethod['amount'] ?? 0,
                'base_amount'   => $shippingMethod['base_amount'] ?? 0,
                'updated_at'    => (new \DateTime())->format('Y-m-d H:i:s'),
            ];

            $updateResponse = $this->apiClient->updateUserData(['userData' => $userData], $authToken);

            if ($updateResponse['success']) {
                return ['success' => true, 'message' => 'Shipping method updated successfully'];
            }

            return $this->errorOutput($updateResponse['error'] ?? 'Failed to update shipping method');
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GraphQL UpdateShippingMethod: ' . $e->getMessage());
            return $this->errorOutput('An unexpected error occurred. Please try again.');
        }
    }
}
