<?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: simplyinDeleteParcelLocker mutation
 */
class DeleteParcelLocker 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'] ?? '');
        $lockerId  = trim($args['locker_id'] ?? '');

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

            $updatedUserData = $this->removeParcelLocker($userData, $lockerId);

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

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

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

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

    /**
     * Find and remove a parcel locker from user data
     *
     * @param array $userData
     * @param mixed $lockerId
     * @return array|null Updated user data, or null if the locker was not found
     */
    private function removeParcelLocker(array $userData, $lockerId): ?array
    {
        if (isset($userData['parcelLockers'])) {
            foreach ($userData['parcelLockers'] as $k => $existing) {
                if (isset($existing['_id']) && $existing['_id'] == $lockerId) {
                    unset($userData['parcelLockers'][$k]);
                    $userData['parcelLockers'] = array_values($userData['parcelLockers']);
                    return $userData;
                }
            }
        }

        return null;
    }
}
