<?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\StoredObjectRepositoryInterface;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * Represents a cron job that removes expired stored objects.
 *
 * This cronjob is executed every 7days, to remove expired stored object. For every
 * expired stored object, every version is sent to message bus for async deletion.
 */
final readonly class RemoveExpiredStoredObjectCronJob implements CronJobInterface
{
    public const KEY = 'remove-expired-stored-object';

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

    public function __construct(
        private ClockInterface $clock,
        private MessageBusInterface $messageBus,
        private StoredObjectRepositoryInterface $storedObjectRepository,
    ) {}

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

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

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

    public function run(array $lastExecutionData): ?array
    {
        $lastDeleted = $lastExecutionData[self::LAST_DELETED_KEY] ?? 0;

        foreach ($this->storedObjectRepository->findByExpired($this->clock->now()) as $storedObject) {
            foreach ($storedObject->getVersions() as $version) {
                $this->messageBus->dispatch(new RemoveOldVersionMessage($version->getId()));
            }
            $lastDeleted = max($lastDeleted, $storedObject->getId());
        }

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