<?php

namespace App\Monitor\Action\Handler;

use App\Monitor\Action\Command\AddMonitorCommand;
use App\Monitor\Action\Result\AddMonitorResult;
use App\Monitor\Framework\Entity\Monitor;
use App\Monitor\Framework\Repository\MonitorRepository;
use App\User\Framework\Repository\UserRepository;
use DateTimeImmutable;
use OneToMany\RichBundle\Contract\CommandInterface;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface;

/** @implements HandlerInterface<AddMonitorCommand> */
readonly class AddMonitorHandler implements HandlerInterface
{
    public function __construct(
        private MonitorRepository $movieMonitorRepository,
        private UserRepository $userRepository,
    ) {}

    public function handle(CommandInterface $command): ResultInterface
    {
        $user = $this->userRepository->find($command->userId);
        $monitor = (new Monitor())
            ->setUser($user)
            ->setTmdbId($command->tmdbId)
            ->setImdbId($command->imdbId)
            ->setTitle($command->title)
            ->setMonitorType($command->monitorType)
            ->setSeason($command->season)
            ->setEpisode($command->episode)
            ->setCreatedAt(new DateTimeImmutable())
            ->setSearchCount(0)
            ->setStatus('New');

        $this->movieMonitorRepository->getEntityManager()->persist($monitor);
        $this->movieMonitorRepository->getEntityManager()->flush();

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