<?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\MainBundle\Entity\User;
use Chill\TicketBundle\Action\Ticket\SetPersonsCommand;
use Chill\TicketBundle\Entity\PersonHistory;
use Chill\TicketBundle\Entity\Ticket;
use Chill\TicketBundle\Event\PersonsUpdateEvent;
use Chill\TicketBundle\Event\TicketUpdateEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

final readonly class SetPersonsCommandHandler
{
    public function __construct(
        private ClockInterface $clock,
        private EntityManagerInterface $entityManager,
        private Security $security,
        private EventDispatcherInterface $eventDispatcher,
    ) {}

    public function handle(Ticket $ticket, SetPersonsCommand $command): void
    {
        $event = new PersonsUpdateEvent($ticket);

        // remove existing addresses which are not in the new addresses
        foreach ($ticket->getPersonHistories() as $personHistory) {
            if (null !== $personHistory->getEndDate()) {
                continue;
            }

            if (!in_array($personHistory->getPerson(), $command->persons, true)) {
                $personHistory->setEndDate($this->clock->now());
                if (($user = $this->security->getUser()) instanceof User) {
                    $personHistory->setRemovedBy($user);
                }
                $event->personsRemoved[] = $personHistory->getPerson();
            }
        }

        // add new addresses
        foreach ($command->persons as $person) {
            if (in_array($person, $ticket->getPersons(), true)) {
                continue;
            }

            $history = new PersonHistory($person, $ticket, $this->clock->now());
            $this->entityManager->persist($history);
            $event->personsAdded[] = $person;
        }

        if ($event->hasChanges()) {
            $this->eventDispatcher->dispatch($event, TicketUpdateEvent::class);
        }
    }
}
