<?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\PersonBundle\Controller;

use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Timeline\TimelineBuilder;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;

class TimelinePersonController extends AbstractController
{
    public function __construct(protected EventDispatcherInterface $eventDispatcher, protected TimelineBuilder $timelineBuilder, protected PaginatorFactory $paginatorFactory, private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    #[\Symfony\Component\Routing\Annotation\Route(path: '/{_locale}/person/{person_id}/timeline', name: 'chill_person_timeline')]
    public function personAction(Request $request, mixed $person_id)
    {
        $person = $this->managerRegistry
            ->getRepository(Person::class)
            ->find($person_id);

        if (null === $person) {
            throw $this->createNotFoundException();
        }

        $this->denyAccessUnlessGranted(PersonVoter::SEE, $person);

        $nbItems = $this->timelineBuilder->countItems(
            'person',
            ['person' => $person]
        );

        $paginator = $this->paginatorFactory->create($nbItems);

        $event = new PrivacyEvent($person, ['action' => 'timeline']);
        $this->eventDispatcher->dispatch($event, PrivacyEvent::PERSON_PRIVACY_EVENT);

        return $this->render(
            '@ChillPerson/Timeline/index.html.twig',
            [
                'timeline' => $this->timelineBuilder->getTimelineHTML(
                    'person',
                    ['person' => $person],
                    $paginator->getCurrentPage()->getFirstItemNumber(),
                    $paginator->getItemsPerPage()
                ),
                'person' => $person,
                'nb_items' => $nbItems,
                'paginator' => $paginator,
            ]
        );
    }
}
