<?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\Enum\PaymentStatus;
use Ferienpass\CoreBundle\Repository\PaymentRepository;
use Symfony\Component\Workflow\WorkflowInterface;

#[AsCronJob('daily')]
class TruncatePayments
{
    public function __construct(private readonly PaymentRepository $payments, private readonly WorkflowInterface $paymentStateMachine, private readonly EntityManagerInterface $entityManager)
    {
    }

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

        $qb = $this->payments->createQueryBuilder('payment');
        $entities = $qb
            ->where($qb->expr()->orX('payment.status = :status', 'payment.status IS NULL'))
            ->andWhere('payment.createdAt <= :date')
            ->setParameter('status', PaymentStatus::CREATED)
            ->setParameter('date', new \DateTimeImmutable('-30 days'))
        ;

        foreach ($entities as $entity) {
            $this->paymentStateMachine->apply($entity, PaymentStatus::TRANSITION_ABANDON);
        }

        $this->entityManager->flush();
    }
}
