<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\EventSubscriber;

use Mautic\CoreBundle\CoreEvents;
use Mautic\CoreBundle\Event\CustomTemplateEvent;
use Mautic\LeadBundle\Entity\Company;
use MauticPlugin\DealFlowBundle\Entity\DealRepository;
use MauticPlugin\DealFlowBundle\Service\DealAuthorization;
use MauticPlugin\DealFlowBundle\Service\DealContextBuilder;
use MauticPlugin\DealFlowBundle\Service\LicenseService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Routing\RouterInterface;

final class CompanyViewSubscriber implements EventSubscriberInterface
{
    private const COMPANY_TEMPLATE = '@MauticLead/Company/company.html.twig';
    private const OVERRIDE_TEMPLATE = '@DealFlow/Company/company.html.twig';
    private const COMPANY_DEAL_LIMIT = 6;

    public function __construct(
        private readonly DealRepository $dealRepository,
        private readonly DealAuthorization $dealAuthorization,
        private readonly DealContextBuilder $dealContextBuilder,
        private readonly RouterInterface $router,
        private readonly LicenseService $licenseService,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            CoreEvents::VIEW_INJECT_CUSTOM_TEMPLATE => ['onViewInjectCustomTemplate', -255],
        ];
    }

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

        if (self::COMPANY_TEMPLATE !== $event->getTemplate()) {
            return;
        }

        $vars = $event->getVars();
        $company = $vars['company'] ?? null;
        if (!$company instanceof Company || null === $company->getId()) {
            return;
        }

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

        $currentUserId = $this->dealAuthorization->getCurrentUserId();
        $includeOtherDeals = $this->dealAuthorization->canViewOtherDeals();

        $companyDeals = [];
        $companyDealContexts = [];
        $companyDealCount = 0;
        $companyDealsUrl = null;

        if ($includeOtherDeals || null !== $currentUserId) {
            $companyId = (int) $company->getId();

            $companyDeals = $this->dealRepository->findByCompany(
                $companyId,
                $currentUserId,
                $includeOtherDeals,
                self::COMPANY_DEAL_LIMIT
            );
            $companyDealCount = $this->dealRepository->countByCompany($companyId, $currentUserId, $includeOtherDeals);
            $companyDealContexts = $this->dealContextBuilder->buildForDeals($companyDeals);
            $companyDealsUrl = $this->router->generate('mautic_dealflow_index', [
                'page' => 1,
                'companyId' => $companyId,
            ]);
        }

        $vars['dealflowCanViewCompanyDeals'] = true;
        $vars['dealflowCompanyDeals'] = $companyDeals;
        $vars['dealflowCompanyDealContexts'] = $companyDealContexts;
        $vars['dealflowCompanyDealCount'] = $companyDealCount;
        $vars['dealflowCompanyDealsUrl'] = $companyDealsUrl;

        $event->setVars($vars);
        $event->setTemplate(self::OVERRIDE_TEMPLATE);
    }
}
