<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\EventSubscriber;

use Mautic\LeadBundle\Event\LeadTimelineEvent;
use Mautic\LeadBundle\LeadEvents;
use MauticPlugin\DealFlowBundle\Entity\DealContactAssociationRepository;
use MauticPlugin\DealFlowBundle\Service\LicenseService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final class ContactTimelineSubscriber implements EventSubscriberInterface
{
    private const EVENT_TYPE_KEY = 'dealflow.deal_associated';

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

    public static function getSubscribedEvents(): array
    {
        return [
            LeadEvents::TIMELINE_ON_GENERATE => ['onTimelineGenerate', 0],
        ];
    }

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

        $eventTypeName = $this->translator->trans('dealflow.timeline.event_type');
        $event->addEventType(self::EVENT_TYPE_KEY, $eventTypeName);

        if (!$event->isApplicable(self::EVENT_TYPE_KEY)) {
            return;
        }

        $leadId = $event->getLeadId();
        if (null === $leadId) {
            return;
        }

        $associations = $this->associationRepository->findByContactForTimeline($leadId);

        $event->addToCounter(self::EVENT_TYPE_KEY, count($associations));

        if ($event->isEngagementCount()) {
            return;
        }

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

            $stage = $deal->getStage();
            $stageName = null !== $stage ? $stage->getName() : null;

            $event->addEvent([
                'event' => self::EVENT_TYPE_KEY,
                'eventId' => self::EVENT_TYPE_KEY.$association->getId(),
                'eventLabel' => [
                    'label' => $deal->getTitle(),
                    'href' => $this->router->generate('mautic_dealflow_view', ['objectId' => $deal->getId()]),
                ],
                'eventType' => $eventTypeName,
                'timestamp' => $association->getCreatedAt(),
                'icon' => 'ri-briefcase-4-line',
                'contactId' => $leadId,
                'contentTemplate' => '@DealFlow/Timeline/deal.html.twig',
                'extra' => [
                    'deal' => $deal,
                    'stage' => $stageName,
                    'amount' => $deal->getAmount(),
                    'currency' => $deal->getCurrency(),
                    'status' => $deal->getStatus(),
                    'role' => $association->getLabel(),
                ],
            ]);
        }
    }
}
