<?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\Command;

use Ferienpass\CoreBundle\Entity\Payment;
use Ferienpass\CoreBundle\Message\FetchPmPaymentStatus;
use Ferienpass\CoreBundle\Repository\PaymentRepository;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Messenger\MessageBusInterface;

#[AsCommand(name: 'pmpayment:fetch-status', description: 'Fetches the transaction status for payments without a status yet (no updates, only creates).')]
final class PmPaymentFetchStatusCommand extends Command
{
    public function __construct(private readonly PaymentRepository $payments, private readonly MessageBusInterface $commandBus)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('id', InputArgument::OPTIONAL, 'Limit to a specific payment id')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $id = $input->getArgument('id');

        $qb = $this->payments->createQueryBuilder('payment')
            ->andWhere('payment.pmPaymentTransactionId IS NOT NULL')
            ->andWhere('payment.pmPaymentTransactionStatus IS NULL')
        ;

        if (null !== $id && '' !== (string) $id) {
            $qb->andWhere('payment.id = :id')->setParameter('id', (int) $id);
        }

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

        $count = 0;
        foreach ($entities as $payment) {
            $txid = $payment->getPmPaymentTransactionId();
            if (null === $txid || '' === $txid || '0' === $txid) {
                continue;
            }

            $this->commandBus->dispatch(new FetchPmPaymentStatus($txid));
            ++$count;
        }

        $output->writeln(\sprintf('Dispatched %d FetchPmPaymentStatus message(s).', $count));

        return Command::SUCCESS;
    }
}
