<?php

namespace App\Download\Action\Handler;

use App\Download\Action\Command\DeleteDownloadCommand;
use App\Download\Action\Result\DeleteDownloadResult;
use App\Download\DownloadEvents;
use App\Download\Framework\Repository\DownloadRepository;
use App\EventLog\Action\Command\AddEventLogCommand;
use App\Library\Action\Command\DeleteMediaFileCommand;
use App\Library\Action\Handler\DeleteMediaFileHandler;
use App\Monitor\MonitorEvents;
use OneToMany\RichBundle\Contract\CommandInterface;
use OneToMany\RichBundle\Contract\HandlerInterface;
use OneToMany\RichBundle\Contract\ResultInterface;
use Symfony\Component\Messenger\MessageBusInterface;

/** @implements HandlerInterface<DeleteDownloadCommand, DeleteDownloadResult> */
readonly class DeleteDownloadHandler implements HandlerInterface
{
    public function __construct(
        private MessageBusInterface $bus,
        private DownloadRepository $downloadRepository,
        private DeleteMediaFileHandler $deleteMediaFileHandler,
    ) {}

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

        if (true === $command->deleteFile) {
            $deletedFileResult = $this->deleteMediaFileHandler->handle(new DeleteMediaFileCommand(
                filename: $download->getFilename(),
                downloadId: $command->downloadId
            ));
        }
        $this->downloadRepository->delete($command->downloadId);

        $this->bus->dispatch(new AddEventLogCommand(
            $download->getUser(),
            DownloadEvents::DOWNLOAD_DELETED->type(),
            DownloadEvents::DOWNLOAD_DELETED->message(),
            (array) $download
        ));

        return new DeleteDownloadResult(
            status: 200,
            message: 'Success',
            download: $download,
            deleteMediaFileResult: $deletedFileResult ?? null
        );
    }
}
