<?php

namespace App\Download\Action\Handler;

use App\Download\Action\Command\DownloadMediaCommand;
use App\Download\Action\Command\ResumeDownloadCommand;
use App\Download\Action\Result\ResumeDownloadResult;
use App\Download\Framework\Entity\Download;
use App\Download\Framework\Repository\DownloadRepository;
use OneToMany\RichBundle\Contract\CommandInterface;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface;
use Symfony\Component\Messenger\MessageBusInterface;

/** @implements HandlerInterface<ResumeDownloadCommand, ResumeDownloadResult> */
readonly class ResumeDownloadHandler implements HandlerInterface
{
    public function __construct(
        private DownloadRepository $downloadRepository,
        private MessageBusInterface $messageBus,
    ) {}

    public function handle(CommandInterface $command): ResultInterface
    {
        /** @var Download $download */
        $download = $this->downloadRepository->find($command->downloadId);

        $this->messageBus->dispatch(new DownloadMediaCommand(
            $download->getUrl(),
            $download->getTitle(),
            $download->getFilename(),
            $download->getMediaType(),
            $download->getImdbId(),
            $download->getUser()->getId(),
            $download->getId()
        ));

        return new ResumeDownloadResult(200, 'Success', $download);
    }
}
