<?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: simplyinAddParcelLocker mutation
 */
class AddParcelLocker 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'] ?? '');
        $lockerInput  = $args['parcel_locker'] ?? [];

        if (empty($authToken) || empty($lockerInput)) {
            throw new GraphQlInputException(__('auth_token and parcel_locker 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->upsertLocker($userData, $lockerInput);
            if ($userData === null) {
                return $this->errorOutput('This parcel locker is already in your list');
            }

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

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

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

    /**
     * Build and append the locker to user data, or return null if it already exists
     *
     * @param array $userData
     * @param array $lockerInput
     * @return array|null Updated user data, or null when the locker already exists
     */
    private function upsertLocker(array $userData, array $lockerInput): ?array
    {
        if (!isset($userData['parcelLockers'])) {
            $userData['parcelLockers'] = [];
        }

        // Parity with Woo/Presta: a custom name is optional. Default the display name to the
        // locker id (fallback address) so we never store a nameless parcel locker.
        $lockerId = $lockerInput['locker_id'];
        $fallbackName = (string)($lockerId ?: ($lockerInput['address'] ?? ''));
        $name = trim((string)($lockerInput['name'] ?? '')) ?: $fallbackName;

        $locker = [
            'lockerId'     => $lockerId,
            'providerName' => $lockerInput['provider_name'],
            'name'         => $name,
            'addressName'  => $name,
            'address'      => $lockerInput['address'] ?? '',
            'city'         => $lockerInput['city'] ?? '',
            'postalCode'   => $lockerInput['postal_code'] ?? '',
            'service_type' => $lockerInput['service_type'] ?? '',
        ];

        // Check for duplicate
        foreach ($userData['parcelLockers'] as $existing) {
            if (isset($existing['lockerId']) && $existing['lockerId'] == $locker['lockerId']) {
                return null;
            }
        }

        $userData['parcelLockers'][] = $locker;

        return $userData;
    }
}
