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

/**
 * Add address controller
 *
 * Handles adding new addresses to user's SimplyIN account
 */
class AddAddress 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 add 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'] ?? '';
            $address = $data['address'] ?? [];
            $addressType = $data['addressType'] ?? 'shippingAddresses';

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

            // Validate address data
            $validationErrors = $this->validateAddress($address);
            if (!empty($validationErrors)) {
                return $result->setData([
                    'success' => false,
                    'message' => __('Validation failed'),
                    'errors' => $validationErrors
                ]);
            }

            // 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'];
            }
            
            // Add new address to the appropriate array
            if (!isset($userData[$addressType])) {
                $userData[$addressType] = [];
            }
            
            $userData[$addressType][] = $address;

            // Update user data
            $updateResponse = $this->apiClient->updateUserData(['userData' => $userData], $authToken);
            
            if ($updateResponse['success']) {
                return $result->setData([
                    'success' => true,
                    'message' => __('Address added successfully'),
                    'address' => end($userData[$addressType])
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $updateResponse['error'] ?? __('Failed to add address')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN AddAddress: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }

    /**
     * Validate address data
     *
     * @param array $address
     * @return array
     */
    private function validateAddress($address)
    {
        $errors = [];
        
        if (empty($address['name'])) {
            $errors['name'] = __('First name is required');
        }
        
        if (empty($address['surname'])) {
            $errors['surname'] = __('Last name is required');
        }
        
        if (empty($address['street'])) {
            $errors['street'] = __('Street address is required');
        }
        
        if (empty($address['city'])) {
            $errors['city'] = __('City is required');
        }
        
        if (empty($address['postalCode'])) {
            $errors['postalCode'] = __('Postal code is required');
        }
        
        if (empty($address['country'])) {
            $errors['country'] = __('Country is required');
        }
        
        return $errors;
    }
}
