<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Controller\Api;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Delete parcel locker controller
 *
 * Handles deletion of parcel lockers from user's SimplyIN account
 */
class DeleteParcelLocker implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @var ApiClient
     */
    private $apiClient;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * Constructor
     *
     * @param JsonFactory $resultJsonFactory
     * @param ApiClient $apiClient
     * @param RequestInterface $request
     * @param LoggerInterface $logger
     */
    public function __construct(
        JsonFactory $resultJsonFactory,
        ApiClient $apiClient,
        RequestInterface $request,
        LoggerInterface $logger
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->apiClient = $apiClient;
        $this->request = $request;
        $this->logger = $logger;
    }

    /**
     * Execute delete parcel locker action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        
        try {
            $data = json_decode($this->request->getContent(), true);
            $authToken = $data['authToken'] ?? '';
            $lockerId = $data['lockerId'] ?? '';

            if (empty($authToken) || empty($lockerId)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Auth token and locker ID are required')
                ]);
            }

            // Get current user data
            $userDataResponse = $this->apiClient->getUserData($authToken);
            if (!$userDataResponse['success']) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Failed to get user data')
                ]);
            }

            // Handle nested data structure: API returns { data: { parcelLockers: [...] } }
            $userData = $userDataResponse['data'];
            if (isset($userData['data'])) {
                $userData = $userData['data'];
            }
            
            // Find and remove the parcel locker
            $updatedUserData = $this->removeParcelLocker($userData, $lockerId);

            if ($updatedUserData === null) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Parcel locker not found')
                ]);
            }
            $userData = $updatedUserData;

            // Update user data
            $updateResponse = $this->apiClient->updateUserData(['userData' => $userData], $authToken);
            
            if ($updateResponse['success']) {
                return $result->setData([
                    'success' => true,
                    'message' => __('Parcel locker deleted successfully')
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $updateResponse['error'] ?? __('Failed to delete parcel locker')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN DeleteParcelLocker: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('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 $key => $existingLocker) {
                // Use loose comparison like PrestaShop plugin
                if (isset($existingLocker['_id']) && $existingLocker['_id'] == $lockerId) {
                    unset($userData['parcelLockers'][$key]);
                    // Re-index array to maintain proper structure
                    $userData['parcelLockers'] = array_values($userData['parcelLockers']);
                    return $userData;
                }
            }
        }

        return null;
    }
}
