<?php

namespace App\Controller;

use App\Entity\User;
use App\Service\ConcessionsProvider;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[IsGranted('ROLE_USER')]
final class ConcessionsController extends AbstractController
{
    #[Route('/api/concessions', name: 'app_concessions_get', methods: ['GET'])]
    public function get(): JsonResponse
    {
        /** @var User $user */
        $user = $this->getUser();

        return $this->json(['selected' => $user->getConcessions()]);
    }

    #[Route('/api/concessions', name: 'app_concessions_save', methods: ['POST'])]
    public function save(
        Request $request,
        ConcessionsProvider $provider,
        EntityManagerInterface $em,
    ): JsonResponse {
        /** @var User $user */
        $user = $this->getUser();

        // Le périmètre des rôles restreints est défini par un administrateur (cf. /utilisateurs).
        // On interdit l'auto-élargissement des concessions (sinon escalade de périmètre).
        if (!$user->seesAllConcessions()) {
            return $this->json(['error' => 'Vos concessions sont gérées par un administrateur.'], Response::HTTP_FORBIDDEN);
        }

        $data = json_decode($request->getContent(), true);
        $input = (\is_array($data) && \is_array($data['concessions'] ?? null)) ? $data['concessions'] : [];

        // Ne garder que les concessions valides (anti-injection)
        $valid = array_values(array_filter(
            array_map(static fn ($c) => \is_string($c) ? $c : null, $input),
            static fn (?string $c) => null !== $c && $provider->isValid($c)
        ));

        $user->setConcessions($valid);
        $em->flush();

        return $this->json(['success' => true, 'concessions' => $valid]);
    }
}
