<?php

namespace App\Download\Action\Handler;

use App\Download\Action\Command\DownloadMediaCommand;
use App\Download\Action\Result\DownloadMediaResult;
use App\Download\Framework\Repository\DownloadRepository;
use App\Download\Downloader\DownloaderInterface;
use App\User\Framework\Repository\UserRepository;
use OneToMany\RichBundle\Contract\CommandInterface;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;

/** @implements HandlerInterface<DownloadMediaCommand, DownloadMediaResult> */
readonly class DownloadMediaHandler implements HandlerInterface
{
    public function __construct(
        private DownloaderInterface $downloader,
        private DownloadRepository $downloadRepository,
        private UserRepository $userRepository,
    ) {}

    public function handle(CommandInterface $command): ResultInterface
    {
        if (null === $command->downloadId) {
            $download = $this->downloadRepository->insert(
                $this->userRepository->find($command->userId),
                $command->url,
                $command->title,
                $command->filename,
                $command->imdbId,
                $command->mediaType,
                ""
            );
        } else {
            $download = $this->downloadRepository->find($command->downloadId);
        }

        try {
            if ($download->getStatus() !== 'Paused') {
                $this->downloadRepository->updateStatus($download->getId(), 'In Progress');
            }

            $this->downloader->download(
                $command->mediaType,
                $command->title,
                $command->url,
                $download->getId()
            );

            if ($download->getStatus() !== 'Paused') {
                $this->downloadRepository->updateStatus($download->getId(), 'Complete');
            }

        } catch (\Throwable $exception) {
            throw new UnrecoverableMessageHandlingException($exception->getMessage(), 500);
        }

        return new DownloadMediaResult(200, "Success.");
    }
}
