<?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 Doctrine\DBAL\Connection;
use Symfony\Component\Clock\ClockInterface;

final readonly class RefreshAddressToGeographicalUnitMaterializedViewCronJob implements CronJobInterface
{
    public function __construct(
        private Connection $connection,
        private ClockInterface $clock,
    ) {}

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

        if ($cronJobExecution->getKey() !== $this->getKey()) {
            throw new \UnexpectedValueException();
        }

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

        return $cronJobExecution->getLastStart() < $now->sub(new \DateInterval('P1D'))
            // introduce a random component to ensure a roll when multiple instances are hosted on same machines
            && 0 === random_int(0, 10);
    }

    public function getKey(): string
    {
        return 'refresh-materialized-view-address-to-geog-units';
    }

    public function run(array $lastExecutionData): ?array
    {
        $this->connection->executeQuery('REFRESH MATERIALIZED VIEW view_chill_main_address_geographical_unit');

        return null;
    }
}
