<?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\DBAL\ArrayParameterType;
use Ferienpass\CoreBundle\Message\AccountActivated;
use Ferienpass\CoreBundle\Repository\MessengerLogRepository;
use Ferienpass\CoreBundle\Repository\UserRepository;

#[AsCronJob('daily')]
class TruncateUnactivatedUsers
{
    public function __construct(private readonly UserRepository $users, private readonly MessengerLogRepository $messages)
    {
    }

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

        $qb = $this->users->createQueryBuilder('user');
        $qb
            ->where('user.disable = 1')
            ->andWhere('user.createdAt <= :date')
            ->andWhere(
                $qb->expr()->not(
                    $qb->expr()->exists(
                        $this->messages->createQueryBuilder('m')
                            ->select('1')
                            ->innerJoin('m.users', 'mu')
                            ->where('mu.id = user.id')
                            ->andWhere('m.message = :message')
                            ->getDQL()
                    )
                )
            )
            ->setParameter('date', new \DateTimeImmutable('-4 days'))
            ->setParameter('message', AccountActivated::class)
        ;

        $this->users->createQueryBuilder('user')
            ->delete()
            ->where('user.id IN (:ids)')
            ->setParameter('ids', $qb->getQuery()->getSingleColumnResult(), ArrayParameterType::INTEGER)
            ->getQuery()
            ->execute()
        ;
    }
}
