<?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\Phonenumber\PhonenumberHelper;
use Chill\PersonBundle\Repository\PersonACLAwareRepositoryInterface;
use Chill\ThirdPartyBundle\Repository\ThirdPartyRepository;
use Chill\TicketBundle\Action\Ticket\AssociateByPhonenumberCommand;
use Chill\TicketBundle\Entity\CallerHistory;
use Chill\TicketBundle\Entity\Ticket;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Clock\ClockInterface;

class AssociateByPhonenumberCommandHandler
{
    public function __construct(
        private readonly PersonACLAwareRepositoryInterface $personRepository,
        private readonly ThirdPartyRepository $thirdPartyRepository,
        private readonly PhonenumberHelper $phonenumberHelper,
        private readonly ClockInterface $clock,
        private readonly EntityManagerInterface $entityManager,
    ) {}

    public function __invoke(Ticket $ticket, AssociateByPhonenumberCommand $command): void
    {
        $phone = $this->phonenumberHelper->parse($command->phonenumber);
        $callers = [
            ...$this->personRepository->findByPhone($phone),
            ...$this->thirdPartyRepository->findByPhonenumber($phone),
        ];

        if (count($callers) > 0) {
            $history = new CallerHistory($callers[0], $ticket, $this->clock->now());
            $this->entityManager->persist($history);
        }
    }
}
