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

/**
 * Handler for setting the caller of a ticket.
 */
class SetCallerCommandHandler
{
    public function __construct(private readonly ClockInterface $clock) {}

    public function __invoke(Ticket $ticket, SetCallerCommand $command): Ticket
    {
        // If the ticket already has the requested caller, return it without changes
        $currentCaller = $ticket->getCaller();
        if ($currentCaller === $command->caller) {
            return $ticket;
        }

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

        // Create a new caller history with the new caller
        new CallerHistory(
            $command->caller,
            $ticket,
            $this->clock->now(),
        );

        return $ticket;
    }
}
