<?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: simplyinAddAddress mutation
 */
class AddAddress extends AbstractResolver
{
    /**
     * @var ApiClient
     */
    protected 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'] ?? '');
        $addressArgs = $args['address'] ?? [];
        $addressType = $args['address_type'] ?? 'shippingAddresses';

        if (empty($authToken) || empty($addressArgs)) {
            throw new GraphQlInputException(__('auth_token and address 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'];
            }

            $address = $this->mapAddressInput($addressArgs);

            if (!isset($userData[$addressType])) {
                $userData[$addressType] = [];
            }
            $userData[$addressType][] = $address;

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

            if ($updateResponse['success']) {
                $saved = end($userData[$addressType]);
                return [
                    'success' => true,
                    'message' => 'Address added successfully',
                    'address' => $this->buildAddressOutput($saved),
                ];
            }

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

    /**
     * Map GraphQL input to API address format
     *
     * @param array $input
     * @return array
     */
    protected function mapAddressInput(array $input): array
    {
        return [
            'name'             => $input['name'] ?? '',
            'surname'          => $input['surname'] ?? '',
            'street'           => $input['street'] ?? '',
            'appartmentNumber' => $input['appartment_number'] ?? '',
            'city'             => $input['city'] ?? '',
            'postalCode'       => $input['postal_code'] ?? '',
            'country'          => $input['country'] ?? '',
            'county'           => $input['county'] ?? '',
        ];
    }

    /**
     * Build address output from API data
     *
     * @param array $address
     * @return array
     */
    protected function buildAddressOutput(array $address): array
    {
        return [
            'id'               => $address['_id'] ?? null,
            'name'             => $address['name'] ?? null,
            'surname'          => $address['surname'] ?? null,
            'street'           => $address['street'] ?? null,
            'appartment_number' => $address['appartmentNumber'] ?? null,
            'city'             => $address['city'] ?? null,
            'postal_code'      => $address['postalCode'] ?? null,
            'country'          => $address['country'] ?? null,
            'county'           => $address['county'] ?? null,
            'raw_json'         => json_encode($address),
        ];
    }
}
