<?php
declare(strict_types=1);

namespace PayPo\Payment\Controller\Checkout;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Exception\NotFoundException;
use PayPo\Payment\Helper\Data;

/**
 * Landing page the customer is redirected to by PayPo (returnUrl).
 *
 * The order state itself is driven by the server to server notification, this
 * controller only decides which page the customer sees.
 */
class Success implements HttpGetActionInterface
{
    /**
     * @param RequestInterface $request
     * @param RedirectFactory $resultRedirectFactory
     * @param Data $payPoHelper
     */
    public function __construct(
        private readonly RequestInterface $request,
        private readonly RedirectFactory $resultRedirectFactory,
        private readonly Data $payPoHelper
    ) {
    }

    /**
     * @return Redirect
     * @throws NotFoundException
     */
    public function execute()
    {
        $status = (string)$this->request->getParam('status');
        $resultRedirect = $this->resultRedirectFactory->create();

        if ($status === 'OK') {
            return $resultRedirect->setPath('checkout/onepage/success');
        }

        if ($status === 'ERR' && $this->payPoHelper->autoCancel()) {
            return $resultRedirect->setPath('paypo/checkout/cancel');
        }

        throw new NotFoundException(__('PayPo 404'));
    }
}
