<?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\DocStoreBundle\Service\StoredObjectCleaner;

use Chill\DocStoreBundle\Repository\StoredObjectVersionRepository;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\MessageBusInterface;

final readonly class RemoveOldVersionCronJob implements CronJobInterface
{
    public const KEY = 'remove-old-stored-object-version';

    private const LAST_DELETED_KEY = 'last-deleted-stored-object-version-id';

    public const KEEP_INTERVAL = 'P90D';

    public function __construct(
        private ClockInterface $clock,
        private MessageBusInterface $messageBus,
        private StoredObjectVersionRepository $storedObjectVersionRepository,
    ) {}

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

        return $this->clock->now() >= $cronJobExecution->getLastEnd()->add(new \DateInterval('P1D'));
    }

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

    public function run(array $lastExecutionData): ?array
    {
        $deleteBeforeDate = $this->clock->now()->sub(new \DateInterval(self::KEEP_INTERVAL));
        $maxDeleted = $lastExecutionData[self::LAST_DELETED_KEY] ?? 0;

        foreach ($this->storedObjectVersionRepository->findIdsByVersionsOlderThanDateAndNotLastVersionAndNotPointInTime($deleteBeforeDate) as $id) {
            $this->messageBus->dispatch(new RemoveOldVersionMessage($id));
            $maxDeleted = max($maxDeleted, $id);
        }

        return [self::LAST_DELETED_KEY => $maxDeleted];
    }
}
