<?php
declare(strict_types=1);

namespace App\Serializer;

use ApiPlatform\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use App\Entity\Access\Access;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Classe servant à ajouter le groupe de denormalization à la ressource Access par rapport au role de l'utilisateur
 */
final class AccessContextBuilder implements SerializerContextBuilderInterface
{
    public function __construct(
        private SerializerContextBuilderInterface $decorated,
        private AuthorizationCheckerInterface $authorizationChecker,
        private Security $security
)
    { }


    /**
     * @param Request $request
     * @param bool $normalization
     * @param mixed[]|null $extractedAttributes
     * @return mixed[]
     */
    public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array
    {
        $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes);
        $resourceClass = $context['resource_class'] ?? null;

        //On ajoute un nouveau groupe seulement si : la ressource est Access, on est en denormalization, l'utilisateur n'a pas le ROLE_USERS
        //et la denormalization est faite sur l'Access de l'utilisateur connecté
        /** @var Access $access */
        $access = $this->security->getUser();
        if (
            $resourceClass === Access::class &&
            false === $normalization &&
            !$this->authorizationChecker->isGranted('ROLE_USERS') &&
            (int) $request->get('id') === $access->getId()
        ){
            $context['groups'] = $context['groups'] ?? [];
            $context['groups'][] = 'my_access:input';
        }

        return $context;
    }
}
