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

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\PersonBundle\Entity\Person;
use Symfony\Component\HttpFoundation\Response;
use Chill\JobBundle\Entity\Frein;
use Chill\JobBundle\Entity\CV;
use Chill\JobBundle\Entity\Immersion;
use Chill\JobBundle\Entity\ProjetProfessionnel;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\JobBundle\Security\Authorization\JobVoter;

class CSReportController extends AbstractController
{
    public function __construct(private readonly \Doctrine\Persistence\ManagerRegistry $managerRegistry) {}

    #[Route(path: '{_locale}/person/job/{person}/report', name: 'chill_job_report_index')]
    public function index(Person $person): Response
    {
        $this->denyAccessUnlessGranted(PersonVoter::SEE, $person, 'The access to '
            .'person is denied');

        $reports = $this->getReports($person);

        return $this->render('@ChillJob/Report/index.html.twig', \array_merge([
            'person' => $person,
        ], $reports));
    }

    protected function getReports(Person $person): array
    {
        $results = [];

        $kinds = [];

        if ($this->isGranted(JobVoter::REPORT_CV, $person)) {
            $kinds['cvs'] = CV::class;
        }

        if ($this->isGranted(JobVoter::REPORT_NEW, $person)) {
            $kinds = \array_merge($kinds, [
                'cvs' => CV::class,
                'freins' => Frein::class,
                'immersions' => Immersion::class,
                'projet_professionnels' => ProjetProfessionnel::class,
            ]);
        }

        foreach ($kinds as $key => $className) {
            $ordering = match ($key) {
                'immersions' => ['debutDate' => 'DESC'],
                default => ['reportDate' => 'DESC'],
            };
            $results[$key] = $this->managerRegistry->getManager()
                ->getRepository($className)
                ->findBy(['person' => $person], $ordering);
        }

        return $results;
    }
}
