<?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\Notification;

use Chill\MainBundle\Entity\Notification;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Repository\NotificationRepository;
use Symfony\Component\Security\Core\Security;

/**
 * Helps to find if a notification exist for a given entity.
 */
class NotificationPresence
{
    private array $cache = [];

    public function __construct(private readonly Security $security, private readonly NotificationRepository $notificationRepository) {}

    /**
     * @param list<array{relatedEntityClass: class-string, relatedEntityId: int}> $more
     *
     * @return array{unread: int, sent: int, total: int}
     */
    public function countNotificationsForClassAndEntity(string $relatedEntityClass, int $relatedEntityId, array $more = [], array $options = []): array
    {
        if ([] === $more && \array_key_exists($relatedEntityClass, $this->cache) && \array_key_exists($relatedEntityId, $this->cache[$relatedEntityClass])) {
            return $this->cache[$relatedEntityClass][$relatedEntityId];
        }

        $user = $this->security->getUser();

        if ($user instanceof User) {
            $counter = $this->notificationRepository->countNotificationByRelatedEntityAndUserAssociated(
                $relatedEntityClass,
                $relatedEntityId,
                $user,
                $more
            );

            if ([] === $more) {
                $this->cache[$relatedEntityClass][$relatedEntityId] = $counter;
            }

            return $counter;
        }

        return ['unread' => 0, 'sent' => 0, 'total' => 0];
    }

    /**
     * @param list<array{relatedEntityClass: class-string, relatedEntityId: int}> $more
     *
     * @return array|Notification[]
     */
    public function getNotificationsForClassAndEntity(string $relatedEntityClass, int $relatedEntityId, array $more = []): array
    {
        $user = $this->security->getUser();

        if ($user instanceof User) {
            return $this->notificationRepository->findNotificationByRelatedEntityAndUserAssociated(
                $relatedEntityClass,
                $relatedEntityId,
                $user,
                $more
            );
        }

        return [];
    }
}
