<?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\TicketBundle\Menu;

use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\TicketBundle\Repository\TicketRepositoryInterface;
use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Knp\Menu\MenuItem;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Add menu entrie to person menu.
 *
 * Menu entries added :
 *
 * - person details ;
 * - accompanying period (if `visible`)
 *
 * @implements LocalMenuBuilderInterface<array{person: Person}>
 */
class PersonMenuBuilder implements LocalMenuBuilderInterface
{
    public function __construct(
        private readonly AuthorizationCheckerInterface $authorizationChecker,
        private readonly TranslatorInterface $translator,
        private readonly TicketRepositoryInterface $ticketRepository,
    ) {}

    /**
     * @param array{person: Person} $parameters
     *
     * @return void
     */
    public function buildMenu($menuId, MenuItem $menu, array $parameters)
    {
        /** @var Person $person */
        $person = $parameters['person'];

        if ($this->authorizationChecker->isGranted(PersonVoter::SEE, $person)) {
            $menu->addChild($this->translator->trans('chill_ticket.list.title_menu'), [
                'route' => 'chill_person_ticket_list',
                'routeParameters' => [
                    'id' => $person->getId(),
                ],
            ])
                ->setExtras([
                    'order' => 150,
                    'counter' => 0 < ($nbTickets = $this->ticketRepository->countOpenedByPerson($person))
                        ? $nbTickets : null,
                ]);
        }
    }

    public static function getMenuIds(): array
    {
        return ['person'];
    }
}
