<?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: simplyinDeleteAddress mutation
 */
class DeleteAddress 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'] ?? '');
        $addressId   = trim($args['address_id'] ?? '');
        $addressType = $args['address_type'] ?? 'shippingAddresses';

        if (empty($authToken) || empty($addressId)) {
            throw new GraphQlInputException(__('auth_token and address_id 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 = $this->removeAddress($userData, $addressType, $addressId);
            if ($userData === null) {
                return $this->errorOutput('Address not found');
            }

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

            if ($updateResponse['success']) {
                return ['success' => true, 'message' => 'Address deleted successfully'];
            }

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

    /**
     * Remove an address from the user's address book.
     *
     * @param array $userData
     * @param string $addressType
     * @param mixed $addressId
     * @return array|null Updated user data, or null when the address was not found
     */
    private function removeAddress(array $userData, string $addressType, $addressId): ?array
    {
        if (!isset($userData[$addressType])) {
            return null;
        }

        foreach ($userData[$addressType] as $k => $existing) {
            if (isset($existing['_id']) && $existing['_id'] == $addressId) {
                unset($userData[$addressType][$k]);
                $userData[$addressType] = array_values($userData[$addressType]);
                return $userData;
            }
        }

        return null;
    }
}
