<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Export\Cronjob;

use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Chill\MainBundle\Export\Messenger\RemoveExportGenerationMessage;
use Chill\MainBundle\Repository\ExportGenerationRepository;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;

final readonly class RemoveExpiredExportGenerationCronJob implements CronJobInterface
{
    public const KEY = 'remove-expired-export-generation';

    public function __construct(private ClockInterface $clock, private ExportGenerationRepository $exportGenerationRepository, private MessageBusInterface $messageBus) {}

    public function canRun(?CronJobExecution $cronJobExecution): bool
    {
        if (null === $cronJobExecution) {
            return true;
        }

        return $cronJobExecution->getLastStart()->getTimestamp() < $this->clock->now()->sub(new \DateInterval('PT24H'))->getTimestamp();
    }

    public function getKey(): string
    {
        return self::KEY;
    }

    public function run(array $lastExecutionData): ?array
    {
        $now = $this->clock->now();

        foreach ($this->exportGenerationRepository->findExpiredExportGeneration($now) as $exportGeneration) {
            $this->messageBus->dispatch(new Envelope(new RemoveExportGenerationMessage($exportGeneration)));
        }

        return ['last-deletion' => $now->getTimestamp()];
    }
}
