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

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

class StoredObjectApiController extends ApiController
{
    public function __construct(
        private readonly Security $security,
        private readonly SerializerInterface $serializer,
        private readonly EntityManagerInterface $entityManager,
    ) {}

    /**
     * Creates a new stored object.
     *
     * @return JsonResponse the response containing the serialized object in JSON format
     *
     * @throws AccessDeniedHttpException if the user does not have the necessary role to create a stored object
     */
    #[Route('/api/1.0/doc-store/stored-object/create', methods: ['POST'])]
    public function createStoredObject(): JsonResponse
    {
        if (!($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_USER'))) {
            throw new AccessDeniedHttpException('Must be user or admin to create a stored object');
        }

        $object = new StoredObject();

        $this->entityManager->persist($object);
        $this->entityManager->flush();

        return new JsonResponse(
            $this->serializer->serialize($object, 'json', [AbstractNormalizer::GROUPS => ['read']]),
            json: true
        );
    }
}
