<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Twig;

use Ferienpass\CoreBundle\Repository\ConversationItemRepository;
use Symfony\Bundle\SecurityBundle\Security;
use Twig\Attribute\AsTwigFunction;

class ConversationExtension
{
    public function __construct(
        private readonly ConversationItemRepository $repository,
        private readonly Security $security,
    ) {
    }

    /**
     * Comment counts for a page of list rows, keyed by row id.
     *
     * The list layouts call this once per page and hand the map down to the
     * row templates, which would otherwise count each row's EXTRA_LAZY
     * `conversation` collection separately — one query per row.
     *
     * @param iterable<mixed> $items
     *
     * @return array<int, int>
     */
    #[AsTwigFunction('conversation_counts')]
    public function counts(iterable $items): array
    {
        // Mirrors the guard in the row templates: nobody else sees the
        // comment indicator, so nobody else needs the query.
        if (!$this->security->isGranted('ROLE_ADMIN') && !$this->security->isGranted('ROLE_PARTICIPANTS_ADMIN')) {
            return [];
        }

        return $this->repository->countForSubjects($items);
    }
}
