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

use Chill\DocStoreBundle\Security\Authorization\AccompanyingCourseDocumentVoter;
use Chill\DocStoreBundle\Security\Authorization\PersonDocumentVoter;
use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Knp\Menu\MenuItem;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;

final readonly class MenuBuilder implements LocalMenuBuilderInterface
{
    public function __construct(private Security $security, private TranslatorInterface $translator) {}

    public function buildMenu($menuId, MenuItem $menu, array $parameters)
    {
        match ($menuId) {
            'accompanyingCourse' => $this->buildMenuAccompanyingCourse($menu, $parameters),
            'person' => $this->buildMenuPerson($menu, $parameters),
            default => throw new \LogicException("this menuid {$menuId} is not implemented"),
        };
    }

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

    private function buildMenuAccompanyingCourse(MenuItem $menu, array $parameters)
    {
        $course = $parameters['accompanyingCourse'];

        if ($this->security->isGranted(AccompanyingCourseDocumentVoter::SEE, $course)) {
            $menu->addChild($this->translator->trans('Documents'), [
                'route' => 'chill_docstore_generic-doc_by-period_index',
                'routeParameters' => [
                    'id' => $course->getId(),
                ],
            ])
                ->setExtras([
                    'order' => 400,
                ]);
        }
    }

    private function buildMenuPerson(MenuItem $menu, array $parameters)
    {
        /** @var \Chill\PersonBundle\Entity\Person $person */
        $person = $parameters['person'];

        if ($this->security->isGranted(PersonDocumentVoter::SEE, $person)) {
            $menu->addChild($this->translator->trans('Documents'), [
                'route' => 'chill_docstore_generic-doc_by-person_index',
                'routeParameters' => [
                    'id' => $person->getId(),
                ],
            ])
                ->setExtras([
                    'order' => 350,
                ]);
        }
    }
}
