<?php

declare(strict_types=1);

namespace App\MessageHandler;

use App\Entity\Device;
use App\Message\AdvanceRotationMessage;
use App\Service\RotationService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class AdvanceRotationMessageHandler
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly RotationService        $rotationService,
        private readonly LoggerInterface        $logger,
    ) {}

    public function __invoke(AdvanceRotationMessage $message): void
    {
        $devices = $this->em->getRepository(Device::class)->findAll();

        foreach ($devices as $device) {
            if (!$this->rotationService->isDue($device)) {
                $this->logger->debug('rotation.not_due', ['device_id' => $device->getId()]);
                continue;
            }

            $image = $this->rotationService->advance($device);
            if ($image === null) {
                $this->logger->info('rotation.no_ready_images', ['device_id' => $device->getId()]);
            }
        }
    }
}
