<?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\Repository\AttendanceExtraFileRepository;

/**
 * The application form stores a file answer the moment it is picked — before the
 * application exists — so an abandoned form leaves a staged row (no attendance)
 * and its bytes behind. Drop those after a day; the removal cascades to the
 * stored object via
 * {@see \Ferienpass\CoreBundle\EventListener\Doctrine\Attendance\AttendanceExtraFileListener}.
 *
 * A day (not an hour) because a form may legitimately sit open for a long while,
 * and adopting a pruned file would silently lose an answer the applicant
 * believed was attached.
 */
#[AsCronJob('daily')]
class PruneStagedExtraFiles
{
    public function __construct(
        private readonly AttendanceExtraFileRepository $files,
        private readonly EntityManagerInterface $entityManager,
    ) {
    }

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

        $stale = $this->files->findStaleStaged(new \DateTimeImmutable('-1 day'));
        if ([] === $stale) {
            return;
        }

        foreach ($stale as $file) {
            $this->entityManager->remove($file);
        }

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