<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\TicketBundle\Action\Ticket\Handler;

use Chill\TicketBundle\Action\Ticket\ChangeEmergencyStateCommand;
use Chill\TicketBundle\Entity\EmergencyStatusHistory;
use Chill\TicketBundle\Entity\Ticket;
use Chill\TicketBundle\Event\EmergencyStatusUpdateEvent;
use Chill\TicketBundle\Event\TicketUpdateEvent;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

/**
 * Handler for changing the emergency status of a ticket.
 */
class ChangeEmergencyStateCommandHandler
{
    public function __construct(
        private readonly ClockInterface $clock,
        private readonly EventDispatcherInterface $eventDispatcher,
    ) {}

    public function __invoke(Ticket $ticket, ChangeEmergencyStateCommand $command): Ticket
    {
        // If the ticket is already in the requested emergency status, return it without changes
        if ($command->newEmergencyStatus === $ticket->getEmergencyStatus()) {
            return $ticket;
        }

        $previous = $ticket->getEmergencyStatus();

        // End the current emergency status history (if any)
        foreach ($ticket->getEmergencyStatusHistories() as $emergencyStatusHistory) {
            if (null === $emergencyStatusHistory->getEndDate()) {
                $emergencyStatusHistory->setEndDate($this->clock->now());
            }
        }

        // Create a new emergency status history with the new status
        new EmergencyStatusHistory(
            $command->newEmergencyStatus,
            $ticket,
            $this->clock->now(),
        );

        // Dispatch event about the toggle
        if (null !== $previous) {
            $event = new EmergencyStatusUpdateEvent($ticket, $previous, $command->newEmergencyStatus);
            $this->eventDispatcher->dispatch($event, TicketUpdateEvent::class);
        }

        return $ticket;
    }
}
