<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Controller\Payment;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\View\Result\PageFactory;
use Simplyin\Payment\Helper\ApiClient;
use Magento\Quote\Api\CartManagementInterface;
use Simplyin\Payment\Service\CheckoutSessionRestorer;
use Psr\Log\LoggerInterface;

/**
 * 3D Secure Return Controller
 *
 * Handles return from 3D Secure authentication
 * Since Magento order is already created before 3DS redirect,
 * this controller redirects to success page where JS will poll payment status
 */
class Return3DS implements HttpGetActionInterface, CsrfAwareActionInterface
{
    /**
     * @var RedirectFactory
     */
    private $resultRedirectFactory;

    /**
     * @var PageFactory
     */
    private $resultPageFactory;

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

    /**
     * @var CartManagementInterface
     */
    private $cartManagement;

    /**
     * @var CheckoutSessionRestorer
     */
    private $checkoutSessionRestorer;

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

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

    /**
     * Constructor
     *
     * @param RedirectFactory $resultRedirectFactory
     * @param PageFactory $resultPageFactory
     * @param ApiClient $apiClient
     * @param CartManagementInterface $cartManagement
     * @param CheckoutSessionRestorer $checkoutSessionRestorer
     * @param LoggerInterface $logger
     * @param RequestInterface $request
     */
    public function __construct(
        RedirectFactory $resultRedirectFactory,
        PageFactory $resultPageFactory,
        ApiClient $apiClient,
        CartManagementInterface $cartManagement,
        CheckoutSessionRestorer $checkoutSessionRestorer,
        LoggerInterface $logger,
        RequestInterface $request
    ) {
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->resultPageFactory = $resultPageFactory;
        $this->apiClient = $apiClient;
        $this->cartManagement = $cartManagement;
        $this->checkoutSessionRestorer = $checkoutSessionRestorer;
        $this->logger = $logger;
        $this->request = $request;
    }

    /**
     * Create CSRF validation exception
     *
     * @param RequestInterface $request
     * @return InvalidRequestException|null
     */
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

    /**
     * Validate request for CSRF
     *
     * @param RequestInterface $request
     * @return bool|null
     */
    public function validateForCsrf(RequestInterface $request): ?bool
    {
        // Always allow - this is a redirect back from 3DS bank authentication
        return true;
    }

    /**
     * Execute 3DS return action
     *
     * Since Magento order is already created before 3DS redirect,
     * we need to restore the checkout session and redirect to success page.
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        $this->logger->info('SimplyIN: 3DS Return - Processing return from 3D Secure');
        
        // Get all possible parameters from URL (payment provider may use different param names)
        $paymentId = $this->request->getParam('paymentId');
        $status = $this->request->getParam('status');
        $statusCode = $this->request->getParam('statusCode');
        $orderId = $this->request->getParam('orderId');
        $reserved = $this->request->getParam('reserved');
        $reqId = $this->request->getParam('reqId');
        
        $this->logger->info('SimplyIN: 3DS Return - Params', [
            'paymentId' => $paymentId,
            'status' => $status,
            'statusCode' => $statusCode,
            'orderId' => $orderId,
            'reserved' => $reserved,
            'reqId' => $reqId
        ]);

        // Try to restore checkout session using all available identifiers
        // Priority: orderId > reserved (increment ID from quote)
        $orderIdentifier = $orderId ?: $reserved;
        $this->checkoutSessionRestorer->restoreCheckoutSession($orderIdentifier);

        // Redirect to success page - the order already exists
        // The success page or checkout page JS will handle payment status polling
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('checkout/onepage/success');
        
        return $resultRedirect;
    }
}
