<?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\CoreBundle\Cron;

use Contao\CoreBundle\Cron\Cron;
use Contao\CoreBundle\DependencyInjection\Attribute\AsCronJob;
use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\Payment;
use Ferienpass\CoreBundle\Entity\PmPaymentTransactionStatus;
use Ferienpass\CoreBundle\Message\FetchPmPaymentStatus;
use Ferienpass\CoreBundle\Repository\PaymentRepository;
use Symfony\Component\Messenger\MessageBusInterface;

#[AsCronJob('daily')]
class RefetchPmPaymentTransactionStatuses
{
    public function __construct(private readonly EntityManagerInterface $entityManager, private readonly MessageBusInterface $commandBus, private readonly PaymentRepository $payments)
    {
    }

    public function __invoke(string $scope): void
    {
        if (Cron::SCOPE_WEB === $scope) {
            return;
        }

        $this->fetchWithNoStatus();
        $this->fetchPending();
    }

    public function fetchWithNoStatus(): void
    {
        $qb = $this->payments->createQueryBuilder('payment');
        $qb = $qb
            ->andWhere('payment.pmPaymentTransactionId IS NOT NULL')
            ->andWhere('payment.pmPaymentTransactionStatus IS NULL')
        ;

        /** @var list<Payment> $entities */
        $entities = $qb->getQuery()->getResult();

        foreach ($entities as $payment) {
            $this->commandBus->dispatch(new FetchPmPaymentStatus($payment->getPmPaymentTransactionId()));
        }
    }

    public function fetchPending(): void
    {
        $repo = $this->entityManager->getRepository(PmPaymentTransactionStatus::class);

        $qb = $repo->createQueryBuilder('s')
            ->where('s.status IN (:statuses)')
            ->setParameter('statuses', [0, -1])
        ;

        /** @var list<PmPaymentTransactionStatus> $entities */
        $entities = $qb->getQuery()->getResult();

        foreach ($entities as $status) {
            $this->commandBus->dispatch(new FetchPmPaymentStatus($status->getTxid()));
        }
    }
}
