<?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 address controller
 *
 * Handles deletion of addresses from user's SimplyIN account
 */
class DeleteAddress 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 address 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'] ?? '';
            $addressId = $data['addressId'] ?? '';
            $addressType = $data['addressType'] ?? 'shippingAddresses';

            if (empty($authToken) || empty($addressId)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Auth token and address 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: { ... } }
            $userData = $userDataResponse['data'];
            if (isset($userData['data'])) {
                $userData = $userData['data'];
            }
            
            // Find and remove the address
            $userData = $this->removeAddress($userData, $addressType, $addressId);
            if ($userData === null) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Address not found')
                ]);
            }

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

        return null;
    }
}
