<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Workflow\Counter;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserGroup;
use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Chill\MainBundle\Repository\Workflow\EntityWorkflowStepRepository;
use Chill\MainBundle\Templating\UI\NotificationCounterInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Workflow\Event\Event;

final readonly class WorkflowByUserCounter implements NotificationCounterInterface, EventSubscriberInterface
{
    public function __construct(private EntityWorkflowStepRepository $workflowStepRepository, private CacheItemPoolInterface $cacheItemPool) {}

    public function addNotification(UserInterface $u): int
    {
        if (!$u instanceof User) {
            return 0;
        }

        $key = self::generateCacheKeyWorkflowByUser($u);
        $item = $this->cacheItemPool->getItem($key);

        if ($item->isHit()) {
            return $item->get();
        }

        $nb = $this->getCountUnreadByUser($u);

        $item->set($nb)
            ->expiresAfter(60 * 15);
        $this->cacheItemPool->save($item);

        return $nb;
    }

    public static function generateCacheKeyWorkflowByUser(User $user): string
    {
        return 'chill_main_workflow_by_u_'.$user->getId();
    }

    public function getCountUnreadByUser(User $user): int
    {
        return $this->workflowStepRepository->countUnreadByUser($user);
    }

    public static function getSubscribedEvents()
    {
        return [
            'workflow.leave' => 'resetWorkflowCache',
        ];
    }

    public function resetWorkflowCache(Event $event): void
    {
        if (!$event->getSubject() instanceof EntityWorkflow) {
            return;
        }

        /** @var EntityWorkflow $entityWorkflow */
        $entityWorkflow = $event->getSubject();
        $step = $entityWorkflow->getCurrentStep();

        if (null === $step) {
            return;
        }

        $keys = [];

        foreach ($step->getDestUser() as $user) {
            $keys[] = self::generateCacheKeyWorkflowByUser($user);
        }
        foreach ($step->getDestUserGroups()->reduce(
            function (array $accumulator, UserGroup $userGroup) {
                foreach ($userGroup->getUsers() as $user) {
                    $accumulator[] = $user;
                }

                return $accumulator;
            },
            []
        ) as $user) {
            $keys[] = self::generateCacheKeyWorkflowByUser($user);
        }

        if ([] !== $keys) {
            $this->cacheItemPool->deleteItems($keys);
        }
    }
}
