<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Controller\Page;

use Contao\CoreBundle\Exception\PageNotFoundException;
use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CmsBundle\Controller\AbstractController;
use Ferienpass\CmsBundle\Fragment\FragmentReference;
use Ferienpass\CoreBundle\Entity\Payment;
use Ferienpass\CoreBundle\Enum\PaymentStatus;
use Ferienpass\CoreBundle\Payments\Provider\PaymentProviderInterface;
use Ferienpass\CoreBundle\Repository\PaymentRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Workflow\Exception\NotEnabledTransitionException;
use Symfony\Component\Workflow\WorkflowInterface;

#[Route('/bezahlen', defaults: ['_requires_payment_provider' => true])]
class PayController extends AbstractController
{
    public function __construct(private readonly PaymentRepository $payments, private readonly PaymentProviderInterface $paymentProvider, private readonly WorkflowInterface $paymentStateMachine, private readonly EntityManagerInterface $entityManager)
    {
    }

    #[Route('/{token}', name: 'cms_pay', priority: -1)]
    public function pay(string $token): Response
    {
        $this->initializeContaoFramework();

        $payment = $this->payments->findPayableByUuid($token);
        if (!$payment instanceof Payment) {
            throw new PageNotFoundException();
        }

        return $this->markPageAsPrivate(
            $this->createPageBuilder()
                ->addFragment('main', new FragmentReference('ferienpass.fragment.pay', ['payment' => $payment]))
                ->getResponse()
        );
    }

    #[Route('/return', name: 'cms_pay_return')]
    public function return(Request $request): Response
    {
        $this->initializeContaoFramework();

        if (!$request->query->count()) {
            throw new PageNotFoundException();
        }

        $txid = $request->query->get('txid');
        /** @var Payment $payment */
        $payment = $this->payments->findOneBy(['pmPaymentTransactionId' => $txid]);
        if (null === $payment) {
            throw new PageNotFoundException();
        }

        $redirectResult = $this->paymentProvider->interpretRedirect($request);

        if (!$payment->isFinalized()) {
            $this->persistPaymentResult($redirectResult, $payment);
        }

        return $this->markPageAsPrivate(
            $this->createPageBuilder()
                ->addFragment('main', new FragmentReference('ferienpass.fragment.pay_return', ['redirectResult' => $redirectResult]))
                ->getResponse()
        );
    }

    #[Route('/check', name: 'cms_pay_check')]
    public function check(Session $session): Response
    {
        $this->initializeContaoFramework();

        if (!$paymentId = $session->get('fp.processPayment')) {
            throw new PageNotFoundException();
        }

        $payment = $this->payments->find($paymentId);

        return $this->markPageAsPrivate(
            $this->createPageBuilder()
                ->addFragment('main', new FragmentReference('ferienpass.fragment.check_payment', ['payment' => $payment]))
                ->getResponse()
        );
    }

    private function persistPaymentResult(int $redirectResult, Payment $payment): void
    {
        try {
            if (PaymentProviderInterface::REDIRECT_PAYMENT_SUCCESS === $redirectResult) {
                $this->paymentStateMachine->apply($payment, PaymentStatus::TRANSITION_PAY);
                $this->entityManager->flush();
            }

            if (PaymentProviderInterface::REDIRECT_PAYMENT_FAILED === $redirectResult) {
                $this->paymentStateMachine->apply($payment, PaymentStatus::TRANSITION_FAIL);
                $this->entityManager->flush();
            }
        } catch (NotEnabledTransitionException) {
        }
    }
}
