<?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\PersonBundle\Controller;

use Chill\ActivityBundle\Entity\Activity;
use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\EventBundle\Entity\Participation;
use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Actions\Remove\PersonMove;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Entity\PersonNotDuplicate;
use Chill\PersonBundle\Form\PersonConfimDuplicateType;
use Chill\PersonBundle\Form\PersonFindManuallyDuplicateType;
use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Repository\PersonNotDuplicateRepository;
use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Search\SimilarPersonMatcher;
use Chill\TaskBundle\Entity\SingleTask;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;

class PersonDuplicateController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
    public function __construct(
        private readonly SimilarPersonMatcher $similarPersonMatcher,
        private readonly PersonRepository $personRepository,
        private readonly PersonMove $personMove,
        private readonly EventDispatcherInterface $eventDispatcher,
        private readonly Security $security,
        private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry,
        private readonly TranslatorInterface $translator,
    ) {}

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person1_id}/duplicate/{person2_id}/confirm', name: 'chill_person_duplicate_confirm')]
    public function confirmAction(mixed $person1_id, mixed $person2_id, Request $request)
    {
        if ($person1_id === $person2_id) {
            throw new \InvalidArgumentException('Can not merge same person');
        }

        $person1 = $this->_getPerson($person1_id);
        $person2 = $this->_getPerson($person2_id);

        $person1->counters = $this->_getCounters($person1_id);
        $person2->counters = $this->_getCounters($person2_id);

        if (null === $person1) {
            throw $this->createNotFoundException("Person with id {$person1_id} not".' found on this server');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_DUPLICATE',
            $person1,
            'You are not allowed to see this person.'
        );

        if (null === $person2) {
            throw $this->createNotFoundException("Person with id {$person2_id} not".' found on this server');
        }

        $form = $this->createForm(PersonConfimDuplicateType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $event = new PrivacyEvent($person1, [
                'element_class' => Person::class,
                'action' => 'move',
            ]);
            $event->addPerson($person2);
            $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

            $sqls = $this->personMove->getSQL($person2, $person1);

            $connection = $this->managerRegistry->getConnection();

            $connection->beginTransaction();

            foreach ($sqls as $sql) {
                $connection->executeQuery($sql);
            }
            $connection->commit();

            return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
        }

        return $this->render('@ChillPerson/PersonDuplicate/confirm.html.twig', [
            'person' => $person1,
            'person2' => $person2,
            'form' => $form->createView(),
        ]);
    }

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/find-manually', name: 'chill_person_find_manually_duplicate')]
    public function findManuallyDuplicateAction(mixed $person_id, Request $request)
    {
        $person = $this->_getPerson($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found on this server');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_DUPLICATE',
            $person,
            'You are not allowed to see this person.'
        );

        $form = $this->createForm(PersonFindManuallyDuplicateType::class);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $person2 = $form->get('person')->getData();

            if (null === $person2) {
                throw $this->createNotFoundException('Person not found on this server');
            }

            // Validation: Ensure person1 is not the same as person2
            if ($person->getId() === $person2->getId()) {
                $this->addFlash('error', $this->translator->trans('Person1 cannot be the same as Person2'));

                return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person2->getId()]);
            }

            $direction = $form->get('direction')->getData();

            if ('starting' === $direction) {
                $params = [
                    'person1_id' => $person->getId(),
                    'person2_id' => $person2->getId(),
                ];
            } else {
                $params = [
                    'person1_id' => $person2->getId(),
                    'person2_id' => $person->getId(),
                ];
            }

            return $this->redirectToRoute('chill_person_duplicate_confirm', $params);
        }

        return $this->render('@ChillPerson/PersonDuplicate/find_manually.html.twig', [
            'person' => $person,
            'form' => $form->createView(),
        ]);
    }

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person1_id}/duplicate/{person2_id}/not-duplicate', name: 'chill_person_duplicate_not_duplicate')]
    public function notDuplicateAction(mixed $person1_id, mixed $person2_id)
    {
        $user = $this->security->getUser();

        if (!$user instanceof User) {
            throw new AccessDeniedHttpException();
        }

        [$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id);

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_DUPLICATE',
            $person1,
            'You are not allowed to see this person.'
        );

        $personNotDuplicate = $this->managerRegistry->getRepository(PersonNotDuplicate::class)
            ->findOneBy(['person1' => $person1, 'person2' => $person2]);

        if (!$personNotDuplicate instanceof PersonNotDuplicate) {
            $personNotDuplicate = new PersonNotDuplicate();
            $personNotDuplicate->setPerson1($person1);
            $personNotDuplicate->setPerson2($person2);
            $personNotDuplicate->setUser($user);

            $this->managerRegistry->getManager()->persist($personNotDuplicate);
            $this->managerRegistry->getManager()->flush();
        }

        return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
    }

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person1_id}/duplicate/{person2_id}/remove-not-duplicate', name: 'chill_person_remove_duplicate_not_duplicate')]
    public function removeNotDuplicateAction(mixed $person1_id, mixed $person2_id)
    {
        [$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id);

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_DUPLICATE',
            $person1,
            'You are not allowed to see this person.'
        );

        $personNotDuplicate = $this->managerRegistry->getRepository(PersonNotDuplicate::class)
            ->findOneBy(['person1' => $person1, 'person2' => $person2]);

        if ($personNotDuplicate instanceof PersonNotDuplicate) {
            $this->managerRegistry->getManager()->remove($personNotDuplicate);
            $this->managerRegistry->getManager()->flush();
        }

        return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
    }

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/duplicate/view', name: 'chill_person_duplicate_view')]
    public function viewAction(mixed $person_id, PersonNotDuplicateRepository $personNotDuplicateRepository)
    {
        $person = $this->_getPerson($person_id);

        if (null === $person) {
            throw $this->createNotFoundException("Person with id {$person_id} not".' found on this server');
        }

        $this->denyAccessUnlessGranted(
            'CHILL_PERSON_DUPLICATE',
            $person,
            'You are not allowed to see this person.'
        );

        $duplicatePersons = $this->similarPersonMatcher->
            matchPerson($person, 0.5, SimilarPersonMatcher::SIMILAR_SEARCH_ORDER_BY_ALPHABETICAL, false);

        $notDuplicatePersons = $personNotDuplicateRepository->findNotDuplicatePerson($person);

        return $this->render('@ChillPerson/PersonDuplicate/view.html.twig', [
            'person' => $person,
            'duplicatePersons' => $duplicatePersons,
            'notDuplicatePersons' => $notDuplicatePersons,
        ]);
    }

    private function _getCounters($id): ?array
    {
        $em = $this->managerRegistry->getManager();

        $nb_activity = $em->getRepository(Activity::class)->findBy(['person' => $id]);
        $nb_document = $em->getRepository(PersonDocument::class)->findBy(['person' => $id]);
        //        $nb_event = $em->getRepository(Participation::class)->findBy(['person' => $id]);
        $nb_task = $em->getRepository(SingleTask::class)->countByParameters(['person' => $id]);
        $person = $em->getRepository(Person::class)->findOneBy(['id' => $id]);

        return [
            'nb_activity' => \count($nb_activity),
            'nb_document' => \count($nb_document),
            //            'nb_event' => count($nb_event),
            'nb_task' => $nb_task,
            'nb_addresses' => \count($person->getAddresses()),
        ];
    }

    /**
     * easy getting a person by his id.
     */
    private function _getPerson(mixed $id): ?Person
    {
        return $this->personRepository->find($id);
    }

    private function _getPersonsByPriority($person1_id, $person2_id)
    {
        if ($person1_id === $person2_id) {
            throw new \InvalidArgumentException('Can not merge same person');
        }

        if ($person1_id > $person2_id) {
            $person1 = $this->_getPerson($person2_id);
            $person2 = $this->_getPerson($person1_id);
        } else {
            $person1 = $this->_getPerson($person1_id);
            $person2 = $this->_getPerson($person2_id);
        }

        if (null === $person1) {
            throw $this->createNotFoundException("Person with id {$person1_id} not".' found on this server');
        }

        if (null === $person2) {
            throw $this->createNotFoundException("Person with id {$person2_id} not".' found on this server');
        }

        return [$person1, $person2];
    }
}
