<?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\DocStoreBundle\Security\Authorization\StoredObjectRoleEnum;
use Chill\DocStoreBundle\Serializer\Normalizer\StoredObjectVersionNormalizer;
use Chill\MainBundle\Pagination\PaginatorFactoryInterface;
use Chill\MainBundle\Serializer\Model\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Order;
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;

final readonly class StoredObjectVersionApiController
{
    public function __construct(
        private PaginatorFactoryInterface $paginatorFactory,
        private SerializerInterface $serializer,
        private Security $security,
    ) {}

    /**
     * Lists the versions of the specified stored object.
     *
     * @param StoredObject $storedObject the stored object whose versions are to be listed
     *
     * @return JsonResponse a JSON response containing the serialized versions of the stored object, encapsulated in a collection
     *
     * @throws AccessDeniedHttpException if the user is not allowed to see the stored object
     */
    #[Route('/api/1.0/doc-store/stored-object/{uuid}/versions', name: 'chill_doc_store_stored_object_versions_list')]
    public function listVersions(StoredObject $storedObject): JsonResponse
    {
        if (!$this->security->isGranted(StoredObjectRoleEnum::SEE->value, $storedObject)) {
            throw new AccessDeniedHttpException('not allowed to see this stored object');
        }

        $total = $storedObject->getVersions()->count();
        $paginator = $this->paginatorFactory->create($total);

        $criteria = Criteria::create();
        $criteria->orderBy(['id' => Order::Ascending]);
        $criteria->setMaxResults($paginator->getItemsPerPage())->setFirstResult($paginator->getCurrentPageFirstItemNumber());
        $items = $storedObject->getVersions()->matching($criteria);

        return new JsonResponse(
            $this->serializer->serialize(
                new Collection(array_values($items->toArray()), $paginator),
                'json',
                [AbstractNormalizer::GROUPS => ['read', StoredObjectVersionNormalizer::WITH_POINT_IN_TIMES_CONTEXT, StoredObjectVersionNormalizer::WITH_RESTORED_CONTEXT]]
            ),
            json: true
        );
    }
}
