<?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\SetAddresseesCommand;
use Chill\TicketBundle\Entity\AddresseeHistory;
use Chill\TicketBundle\Entity\Ticket;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Security\Core\Security;

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

    public function handle(Ticket $ticket, SetAddresseesCommand $command): void
    {
        // remove existing addresses which are not in the new addresses
        foreach ($ticket->getAddresseeHistories() as $addressHistory) {
            if (null !== $addressHistory->getEndDate()) {
                continue;
            }

            if (!in_array($addressHistory->getAddressee(), $command->addressees, true)) {
                $addressHistory->setEndDate($this->clock->now());
                if (($user = $this->security->getUser()) instanceof User) {
                    $addressHistory->setRemovedBy($user);
                }
            }
        }

        // add new addresses
        foreach ($command->addressees as $address) {
            if (in_array($address, $ticket->getCurrentAddressee(), true)) {
                continue;
            }

            $history = new AddresseeHistory($address, $this->clock->now(), $ticket);
            $this->entityManager->persist($history);
        }
    }
}
