<?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: simplyinUpdateAddress mutation
 */
class UpdateAddress extends AddAddress
{
    /**
     * @inheritdoc
     */
    public function resolve(Field $field, $context, ResolveInfo $info, ?array $value = null, ?array $args = null): array
    {
        $authToken   = trim($args['auth_token'] ?? '');
        $addressId   = trim($args['address_id'] ?? '');
        $addressArgs = $args['address'] ?? [];
        $addressType = $args['address_type'] ?? 'shippingAddresses';

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

            $updatedAddress = [];
            $userData = $this->applyAddressUpdate($userData, $addressType, $addressId, $addressArgs, $updatedAddress);

            if ($userData === null) {
                return $this->errorOutput('Address not found');
            }

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

            if ($updateResponse['success']) {
                return [
                    'success' => true,
                    'message' => 'Address updated successfully',
                    'address' => $this->buildAddressOutput($updatedAddress),
                ];
            }

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

    /**
     * Find and update an address in the user's address book.
     *
     * @param array $userData
     * @param string $addressType
     * @param mixed $addressId
     * @param array $addressArgs
     * @param array $updatedAddress Out-param: the merged address when found
     * @return array|null Updated user data, or null when the address was not found
     */
    private function applyAddressUpdate(array $userData, string $addressType, $addressId, array $addressArgs, array &$updatedAddress): ?array
    {
        if (isset($userData[$addressType])) {
            foreach ($userData[$addressType] as $k => $existing) {
                if (isset($existing['_id']) && $existing['_id'] == $addressId) {
                    // Merge only provided fields
                    $patch = array_filter($this->mapAddressInput($addressArgs), fn($val) => $val !== '');
                    // phpcs:ignore Magento2.Performance.ForeachArrayMerge.ForeachArrayMerge -- runs once; immediate return after match, not iterative accumulation
                    $userData[$addressType][$k] = array_merge($existing, $patch);
                    $updatedAddress = $userData[$addressType][$k];
                    return $userData;
                }
            }
        }

        return null;
    }
}
