<?php

namespace App\Monitor\Framework\Controller;

use App\Base\Service\Broadcaster;
use App\Monitor\Action\Handler\AddMonitorHandler;
use App\Monitor\Action\Handler\DeleteMonitorHandler;
use App\Monitor\Action\Input\AddMonitorInput;
use App\Monitor\Action\Input\DeleteMonitorInput;
use App\Monitor\Framework\Scheduler\MonitorDispatcher;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\Routing\Attribute\Route;

class ApiController extends AbstractController
{
    public function __construct(
        private readonly Broadcaster $broadcaster,
    ) {}

    #[Route('/api/monitor', name: 'api_monitor', methods: ['POST'])]
    public function addMonitor(
        AddMonitorInput $input,
        AddMonitorHandler $handler,
        HubInterface $hub,
    ) {
        $command = $input->toCommand();
        $command->userId = $this->getUser()->getId();
        $response = $handler->handle($command);

        $this->broadcaster->alert(
            title: 'Success',
            message: "New monitor added for {$input->title}",
        );

        return $this->json([
            'status' => 200,
            'message' => $response
        ]);
    }

    #[Route('/api/monitor/{monitorId}', name: 'api_monitor_delete', methods: ['DELETE'])]
    public function deleteMonitor(
        DeleteMonitorInput $input,
        DeleteMonitorHandler $handler,
    ) {
        $response = $handler->handle($input->toCommand());

        return $this->json([
            'status' => 200,
            'message' => $response
        ]);
    }

    #[Route('/api/monitor/dispatch', name: 'api_monitor_dispatch', methods: ['GET'])]
    public function dispatch(MonitorDispatcher $dispatcher, Broadcaster $broadcaster): Response
    {
        $dispatcher();

        $broadcaster->alert('Success', 'The monitor job has been dispatched.');

        return $this->json([
            'status' => 200,
            'message' => 'Manually dispatched MonitorDispatcher'
        ]);
    }
}
