<?php

namespace App\Domain\Manga\Application\CommandHandler;

use App\Domain\Manga\Application\Command\CheckMonitoredMangas;
use App\Domain\Manga\Application\Command\RefreshMangaChapters;
use App\Domain\Manga\Application\Query\MonitoringCriteria;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use DateTimeImmutable;
use Symfony\Component\Messenger\MessageBusInterface;

readonly class CheckMonitoredMangasHandler
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository,
        private MessageBusInterface $commandBus
    ) {
    }

    public function handle(CheckMonitoredMangas $command): void
    {
        $criteria = new MonitoringCriteria(
            enabled: true,
            lastCheckBefore: $command->since ?? new DateTimeImmutable('-1 hour')
        );

        $monitoredMangas = $this->mangaRepository->findByMonitoringCriteria($criteria);

        foreach ($monitoredMangas as $manga) {
            $this->commandBus->dispatch(new RefreshMangaChapters($manga->getId()));
        }
    }
}
