<?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 Simplyin\Payment\Service\ParcelLockerFilter;
use Psr\Log\LoggerInterface;

/**
 * Check Push Status controller
 *
 * Polls to check if push notification login was approved
 */
class CheckPushStatus implements HttpPostActionInterface, CsrfAwareActionInterface
{
    use CsrfAwareApiTrait;

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

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

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

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

    /**
     * @var ParcelLockerFilter
     */
    private $parcelLockerFilter;

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

    /**
     * Execute check push status action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultJsonFactory->create();
        
        try {
            $data = json_decode($this->request->getContent(), true);
            $email = $data['email'] ?? '';
            $notificationTokenId = $data['notificationTokenId'] ?? '';

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

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

            // Call SimplyIN API to check push notification status
            $response = $this->apiClient->checkPushStatus($email, $notificationTokenId);

            if ($response['success']) {
                $responseData = $response['data'] ?? [];
                
                // API returns 'ok' field when push notification is confirmed (matching WordPress plugin)
                $approved = isset($responseData['ok']) && $responseData['ok'] === true;
                $authToken = $responseData['authToken'] ?? null;
                $refreshToken = $responseData['refreshToken'] ?? null;
                
                if ($approved && $authToken) {
                    // Get user data from response or fetch it
                    $userData = $this->resolveUserData($responseData, $authToken);

                    return $result->setData([
                        'success' => true,
                        'approved' => true,
                        'authToken' => $authToken,
                        'refreshToken' => $refreshToken,
                        'userData' => $userData,
                        'message' => __('Push notification approved')
                    ]);
                }
                
                // Not approved yet - continue polling
                return $result->setData([
                    'success' => true,
                    'approved' => false,
                    'message' => __('Waiting for approval')
                ]);
            } else {
                $errorCode = $response['error'] ?? 'UNKNOWN_ERROR';

                return $result->setData([
                    'success' => false,
                    'approved' => false,
                    'error' => $errorCode,
                    'message' => $response['error'] ?? __('Failed to check push status')
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN CheckPushStatus: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
            return $result->setData([
                'success' => false,
                'approved' => false,
                'message' => __('An unexpected error occurred. Please try again.')
            ]);
        }
    }

    /**
     * Get user data from response or fetch it using the auth token
     *
     * @param array $responseData
     * @param string $authToken
     * @return array
     */
    private function resolveUserData($responseData, $authToken)
    {
        // Get user data from response or fetch it
        $userData = [];
        if (isset($responseData['userData'])) {
            $userData = $responseData['userData'];
        } else {
            // Fetch user data using auth token
            $userDataResponse = $this->apiClient->getUserData($authToken);
            if ($userDataResponse['success']) {
                // Handle nested data structure: API returns { data: { ... } }
                $userData = $userDataResponse['data'];
                if (isset($userData['data'])) {
                    $userData = $userData['data'];
                }
            }
        }

        if (is_array($userData)) {
            $userData = $this->parcelLockerFilter->filterUserDataParcelLockers($userData);
        }

        return $userData;
    }
}
