<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\EventSubscriber;

use Mautic\CoreBundle\CoreEvents;
use Mautic\CoreBundle\DTO\GlobalSearchFilterDTO;
use Mautic\CoreBundle\Event\CommandListEvent;
use Mautic\CoreBundle\Event\GlobalSearchEvent;
use Mautic\CoreBundle\Security\Permissions\CorePermissions;
use Mautic\CoreBundle\Service\GlobalSearch;
use MauticPlugin\DealFlowBundle\Model\DealModel;
use MauticPlugin\DealFlowBundle\Service\LicenseService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class GlobalSearchSubscriber implements EventSubscriberInterface
{
    private ?GlobalSearch $globalSearch = null;

    public function __construct(
        private readonly DealModel $dealModel,
        private readonly CorePermissions $security,
        private readonly LicenseService $licenseService,
    ) {
    }

    public function setGlobalSearch(GlobalSearch $globalSearch): void
    {
        $this->globalSearch = $globalSearch;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            CoreEvents::GLOBAL_SEARCH => ['onGlobalSearch', 0],
            CoreEvents::BUILD_COMMAND_LIST => ['onBuildCommandList', 0],
        ];
    }

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

        $filterDTO = new GlobalSearchFilterDTO($event->getSearchString());
        $results = $this->globalSearch->performSearch(
            $filterDTO,
            $this->dealModel,
            '@DealFlow/SubscribedEvents/Search/global.html.twig'
        );

        if (!empty($results)) {
            $event->addResults('dealflow.global_search.header', $results);
        }
    }

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

        if ($this->security->isGranted(['dealflow:deals:viewown', 'dealflow:deals:viewother'], 'MATCH_ONE')) {
            $event->addCommands(
                'dealflow.global_search.header',
                $this->dealModel->getCommandList()
            );
        }
    }
}
