<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\EventSubscriber;

use Mautic\CoreBundle\CoreEvents;
use Mautic\CoreBundle\Event\CustomContentEvent;
use MauticPlugin\DealFlowBundle\Entity\DealContactAssociationRepository;
use MauticPlugin\DealFlowBundle\Service\DealAuthorization;
use MauticPlugin\DealFlowBundle\Service\LicenseService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\RouterInterface;

final class ContactViewSubscriber implements EventSubscriberInterface
{
    private const LEAD_TEMPLATE = '@MauticLead/Lead/lead.html.twig';

    public function __construct(
        private readonly DealContactAssociationRepository $associationRepository,
        private readonly DealAuthorization $dealAuthorization,
        private readonly RouterInterface $router,
        private readonly LicenseService $licenseService,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            CoreEvents::VIEW_INJECT_CUSTOM_CONTENT => ['onCustomContent', 0],
        ];
    }

    public function onCustomContent(CustomContentEvent $event): void
    {
        if (!$this->licenseService->isLicensed()) {
            return;
        }

        if (self::LEAD_TEMPLATE !== $event->getViewName()) {
            return;
        }

        if (!$this->dealAuthorization->canViewDeals()) {
            return;
        }

        $vars = $event->getVars();
        $lead = $vars['lead'] ?? null;
        if (!is_object($lead) || !method_exists($lead, 'getId') || null === $lead->getId()) {
            return;
        }

        $context = $event->getContext();
        if ('tabs' !== $context && 'tabs.content' !== $context) {
            return;
        }

        $contactId = (int) $lead->getId();
        $associations = $this->associationRepository->findByContactForTimeline($contactId);

        if ('tabs' === $context) {
            $event->addTemplate('@DealFlow/Lead/_deals_tab.html.twig', [
                'dealflowContactDealCount' => count($associations),
            ]);

            return;
        }

        $deals = [];
        foreach ($associations as $association) {
            $deal = $association->getDeal();
            if (null === $deal) {
                continue;
            }

            $deals[] = [
                'deal' => $deal,
                'role' => $association->getLabel(),
                'viewUrl' => $this->router->generate('mautic_dealflow_view', ['objectId' => $deal->getId()]),
            ];
        }

        $event->addTemplate('@DealFlow/Lead/_deals_tab_content.html.twig', [
            'dealflowContactDeals' => $deals,
        ]);
    }
}
