<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Controller\Page;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\AdminBundle\Breadcrumb\Breadcrumb;
use Ferienpass\AdminBundle\Routing\Base58;
use Ferienpass\CoreBundle\Entity\ParticipantDuplicate;
use Ferienpass\CoreBundle\Participant\ParticipantMerger;
use Ferienpass\CoreBundle\Repository\ParticipantRepositoryInterface;
use FOS\HttpCacheBundle\Configuration\InvalidatePath;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Security\Http\Attribute\IsGranted;
use Symfony\Component\Uid\Uuid;
use Symfony\UX\Turbo\TurboBundle;

#[IsGranted('ROLE_PARTICIPANTS_ADMIN')]
#[Route('/teilnehmende/duplikate')]
final class ParticipantDuplicatesController extends AbstractController
{
    public function __construct(
        private readonly ParticipantRepositoryInterface $participants,
        private readonly EntityManagerInterface $entityManager,
        private readonly ParticipantMerger $participantMerger
    ) {
    }

    #[Route('', name: 'admin_participant_duplicates')]
    public function index(Breadcrumb $breadcrumb): Response
    {
        return $this->render('@FerienpassAdmin/page/participants/duplicates.html.twig', [
            'qb' => $this->participants->queryAllDuplicates(),
            'searchable' => ['p1.firstname', 'p1.lastname', 'p2.firstname', 'p2.lastname'],
            'breadcrumb' => $breadcrumb->generate(
                ['participants.title', ['route' => 'admin_participants_index']],
                'participants.duplicates'
            ),
        ]);
    }

    #[Route('/{uuid1}/{uuid2}/ignore', name: 'admin_participant_duplicates_ignore_modal', requirements: ['uuid1' => Base58::UUID, 'uuid2' => Base58::UUID])]
    #[Route('/{uuid1}/{uuid2}/ignore', name: 'admin_participant_duplicates_ignore_modal_legacy', requirements: ['uuid1' => Requirement::UUID, 'uuid2' => Requirement::UUID])]
    #[InvalidatePath('/admin/teilnehmende/duplikate')]
    public function ignoreModal(Uuid $uuid1, Uuid $uuid2, Request $request): Response
    {
        $p1 = $this->participants->findByUuid($uuid1);
        $p2 = $this->participants->findByUuid($uuid2);

        if (null === $p1 || null === $p2) {
            throw $this->createNotFoundException();
        }

        if ($request->isMethod('POST')) {
            $p1Id = $p1->getId();
            $p2Id = $p2->getId();

            $p1->addDuplicate($p2, ParticipantDuplicate::TYPE_IGNORED);
            $p2->addDuplicate($p1, ParticipantDuplicate::TYPE_IGNORED);
            $this->entityManager->flush();

            if (TurboBundle::STREAM_FORMAT === $request->getPreferredFormat()) {
                $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

                return $this->renderBlock('@FerienpassAdmin/page/participants/duplicates.html.twig', 'ignore_success_stream', [
                    'p1' => $p1,
                    'p2' => $p2,
                    'p1_id' => $p1Id,
                    'p2_id' => $p2Id,
                ]);
            }

            return $this->redirectToRoute('admin_participant_duplicates');
        }

        return $this->render('@FerienpassAdmin/fragment/participants/ignore_modal.html.twig', [
            'p1' => $p1,
            'p2' => $p2,
        ]);
    }

    #[Route('/{uuid1}/{uuid2}/tolerate', name: 'admin_participant_duplicates_tolerate_modal', requirements: ['uuid1' => Base58::UUID, 'uuid2' => Base58::UUID])]
    #[Route('/{uuid1}/{uuid2}/tolerate', name: 'admin_participant_duplicates_tolerate_modal_legacy', requirements: ['uuid1' => Requirement::UUID, 'uuid2' => Requirement::UUID])]
    #[InvalidatePath('/admin/teilnehmende/duplikate')]
    public function tolerateModal(Uuid $uuid1, Uuid $uuid2, Request $request): Response
    {
        $p1 = $this->participants->findByUuid($uuid1);
        $p2 = $this->participants->findByUuid($uuid2);

        if (null === $p1 || null === $p2) {
            throw $this->createNotFoundException();
        }

        if ($request->isMethod('POST')) {
            $p1Id = $p1->getId();
            $p2Id = $p2->getId();

            $p1->addDuplicate($p2, ParticipantDuplicate::TYPE_TOLERATED);
            $p2->addDuplicate($p1, ParticipantDuplicate::TYPE_TOLERATED);
            $this->entityManager->flush();

            if (TurboBundle::STREAM_FORMAT === $request->getPreferredFormat()) {
                $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

                return $this->renderBlock('@FerienpassAdmin/page/participants/duplicates.html.twig', 'tolerate_success_stream', [
                    'p1' => $p1,
                    'p2' => $p2,
                    'p1_id' => $p1Id,
                    'p2_id' => $p2Id,
                ]);
            }

            return $this->redirectToRoute('admin_participant_duplicates');
        }

        return $this->render('@FerienpassAdmin/fragment/participants/tolerate_modal.html.twig', [
            'p1' => $p1,
            'p2' => $p2,
        ]);
    }

    #[Route('/{uuid1}/{uuid2}/merge', name: 'admin_participant_duplicates_merge_modal', requirements: ['uuid1' => Base58::UUID, 'uuid2' => Base58::UUID], priority: 1)]
    #[Route('/{uuid1}/{uuid2}/merge', name: 'admin_participant_duplicates_merge_modal_legacy', requirements: ['uuid1' => Requirement::UUID, 'uuid2' => Requirement::UUID], priority: 1)]
    #[InvalidatePath('/admin/teilnehmende/duplikate')]
    public function mergeModal(Uuid $uuid1, Uuid $uuid2, Request $request): Response
    {
        $p1 = $this->participants->findByUuid($uuid1);
        $p2 = $this->participants->findByUuid($uuid2);

        if (null === $p1 || null === $p2) {
            throw $this->createNotFoundException();
        }

        if ($request->isMethod('POST')) {
            $p1Id = $p1->getId();
            $p2Id = $p2->getId();

            // The merge form submits the chosen participant's base58 UUID as
            // `base`; compare against p2's own base58 (not the route param, so
            // it works regardless of which route variant matched).
            $baseUuid = $request->request->get('base');
            if ($baseUuid === $p2->getUuid()->toBase58()) {
                $base = $p2;
                $merged = $p1;
            } else {
                $base = $p1;
                $merged = $p2;
            }

            $this->participantMerger->merge($merged, $base);

            if (TurboBundle::STREAM_FORMAT === $request->getPreferredFormat()) {
                $request->setRequestFormat(TurboBundle::STREAM_FORMAT);

                return $this->renderBlock('@FerienpassAdmin/page/participants/duplicates.html.twig', 'merge_success_stream', [
                    'p1' => $p1,
                    'p2' => $p2,
                    'p1_id' => $p1Id,
                    'p2_id' => $p2Id,
                ]);
            }

            return $this->redirectToRoute('admin_participant_duplicates');
        }

        return $this->render('@FerienpassAdmin/fragment/participants/merge_modal.html.twig', [
            'p1' => $p1,
            'p2' => $p2,
        ]);
    }
}
