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

use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Symfony\Component\Clock\ClockInterface;

final readonly class CollateAddressWithReferenceOrPostalCodeCronJob implements CronJobInterface
{
    private const LAST_MAX_ID = 'last-max-id';

    public function __construct(
        private ClockInterface $clock,
        private CollateAddressWithReferenceOrPostalCodeInterface $collateAddressWithReferenceOrPostalCode,
    ) {}

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

        $now = $this->clock->now();

        return $now->sub(new \DateInterval('PT6H')) > $cronJobExecution->getLastStart();
    }

    public function getKey(): string
    {
        return 'collate-address';
    }

    public function run(array $lastExecutionData): ?array
    {
        $maxId = ($this->collateAddressWithReferenceOrPostalCode)($lastExecutionData[self::LAST_MAX_ID] ?? 0);

        return [self::LAST_MAX_ID => $maxId];
    }
}
