<?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\ChangeStateCommand;
use Chill\TicketBundle\Entity\StateHistory;
use Chill\TicketBundle\Entity\Ticket;
use Symfony\Component\Clock\ClockInterface;

/**
 * Handler for changing the state of a ticket.
 */
class ChangeStateCommandHandler
{
    public function __construct(private readonly ClockInterface $clock) {}

    public function __invoke(Ticket $ticket, ChangeStateCommand $command): Ticket
    {
        // If the ticket is already in the requested state, return it without changes
        if ($command->newState === $ticket->getState()) {
            return $ticket;
        }

        // End the current state history (if any)
        foreach ($ticket->getStateHistories() as $stateHistory) {
            if (null === $stateHistory->getEndDate()) {
                $stateHistory->setEndDate($this->clock->now());
            }
        }

        // Create a new state history with the new state
        new StateHistory(
            $command->newState,
            $ticket,
            $this->clock->now(),
        );

        return $ticket;
    }
}
