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

/**
 * Get user data controller
 *
 * Retrieves user data from SimplyIN
 */
class GetUserData 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 get user data 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'] ?? '';

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

            $response = $this->apiClient->getUserData($authToken);

            if ($response['success']) {
                // Handle nested data structure: API returns { data: { ... } }
                $userData = $response['data'];
                if (isset($userData['data'])) {
                    $userData = $userData['data'];
                }
                
                return $result->setData([
                    'success' => true,
                    'userData' => $userData,
                    'message' => __('User data retrieved successfully')
                ]);
            } else {
                return $result->setData([
                    'success' => false,
                    'message' => $response['error'] ?? __('Failed to get user data')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN GetUserData: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }
}
