<?php

namespace App\Monitor\Action\Handler;

use App\Download\DownloadEvents;
use App\EventLog\Action\Command\AddEventLogCommand;
use App\Monitor\Action\Command\DeleteMonitorCommand;
use App\Monitor\Action\Result\DeleteMonitorResult;
use App\Monitor\Framework\Repository\MonitorRepository;
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<DeleteMonitorCommand, DeleteMonitorResult> */
readonly class DeleteMonitorHandler implements HandlerInterface
{
    public function __construct(
        private MessageBusInterface $bus,
        private MonitorRepository $monitorRepository,
    ) {}

    public function handle(CommandInterface $command): ResultInterface
    {
        $monitor = $this->monitorRepository->find($command->monitorId);
        $this->monitorRepository->getEntityManager()->remove($monitor);
        $this->monitorRepository->getEntityManager()->flush();

        $this->bus->dispatch(new AddEventLogCommand(
            $monitor->getUser(),
            MonitorEvents::MONITOR_DELETED->type(),
            MonitorEvents::MONITOR_DELETED->message(),
            (array) $monitor
        ));

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