<?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;

/**
 * Search address controller
 *
 * Searches for addresses using SimplyIN API
 */
class SearchAddress 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 search 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'] ?? '';
            // Accept both 'query' and 'searchQuery' parameter names
            $searchQuery = $data['query'] ?? $data['searchQuery'] ?? '';

            if (empty($authToken)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Authentication required')
                ]);
            }

            if (empty($searchQuery)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Search query is required')
                ]);
            }

            $response = $this->apiClient->searchAddress($searchQuery, $authToken);

            if ($response['success']) {
                // Extract addresses array - API returns {data: [...]} structure
                $addresses = $response['data'] ?? [];
                if (isset($addresses['data']) && is_array($addresses['data'])) {
                    $addresses = $addresses['data'];
                }
                
                return $result->setData([
                    'success' => true,
                    'addresses' => $addresses,
                    'message' => __('Addresses found')
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $response['error'] ?? __('Failed to search addresses')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN SearchAddress: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }
}
