<?php

namespace App\Monitor\Action\Handler;

use App\Download\Action\Command\DownloadMediaCommand;
use App\Monitor\Action\Command\MonitorMovieCommand;
use App\Monitor\Action\Result\MonitorMovieResult;
use App\Monitor\Framework\Entity\Monitor;
use App\Monitor\Framework\Repository\MonitorRepository;
use App\Monitor\Service\MonitorOptionEvaluator;
use App\Torrentio\Action\Command\GetMovieOptionsCommand;
use App\Torrentio\Action\Handler\GetMovieOptionsHandler;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use OneToMany\RichBundle\Contract\CommandInterface;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Messenger\MessageBusInterface;

/** @implements HandlerInterface<MonitorMovieCommand> */
readonly class MonitorMovieHandler implements HandlerInterface
{
    public function __construct(
        private MonitorRepository $movieMonitorRepository,
        private GetMovieOptionsHandler $getMovieOptionsHandler,
        private EntityManagerInterface $entityManager,
        private MessageBusInterface $bus,
        private LoggerInterface $logger,
        private Security $security,
    ) {}

    public function handle(CommandInterface $command): ResultInterface
    {
        $this->logger->info('> [MonitorMovieHandler] Executing MonitorMovieHandler');
        /** @var Monitor $monitor */
        $monitor = $this->movieMonitorRepository->find($command->movieMonitorId);
        $monitor->setStatus('In Progress');

        $this->logger->info('> [MonitorMovieHandler] Searching for "' . $monitor->getTitle() . '" download options');
        $results = $this->getMovieOptionsHandler->handle(
            new GetMovieOptionsCommand($monitor->getTmdbId(), $monitor->getImdbId())
        );
        $this->logger->info('> [MonitorMovieHandler] Found ' . count($results->results) . ' download options');

        $result = $this->monitorOptionEvaluator->evaluateOptions($monitor, $results->results);

        if (null !== $result) {
            $this->logger->info('> [MonitorMovieHandler] 1 result found: dispatching DownloadMediaCommand for "' . $result->title . '"');
            $this->bus->dispatch(new DownloadMediaCommand(
                $result->url,
                $monitor->getTitle(),
                $result->filename,
                'movies',
                $monitor->getImdbId(),
                $monitor->getUser()->getId(),
            ));
            $monitor->setStatus('Complete');
            $monitor->setDownloadedAt(new DateTimeIMmutable());
        } else {
            $monitor->setStatus('Active');
        }

        $monitor->setLastSearch(new DateTimeImmutable());
        $monitor->incrementSearchCount();
        $this->entityManager->flush();

        return new MonitorMovieResult(
            status: 'OK',
            result: [
                'monitor' => $monitor,
            ]
        );
    }
}
