<?php

namespace Shared\RightManagement\Provider;

use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Shared\RightManagement\Entity\AbstractAdvancedRight;

/**
 * Class AdvancedRightProvider
 * @package Shared\RightManagement\Provider
 */
class AdvancedRightProvider implements ContextAwareCollectionDataProviderInterface, RestrictedDataProviderInterface
{
    private EntityManagerInterface $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function getCollection(string $resourceClass, string $operationName = null, array $context = []): iterable
    {
        $repository = $this->em->getRepository($resourceClass);
        /** @var QueryBuilder $queryBuilder */
        $queryBuilder = $repository->createQueryBuilder('o');

        $rootAlias = $queryBuilder->getRootAliases()[0];
        foreach ($context['filters'] as $filter => $value) {
            $queryBuilder->andWhere(sprintf('%s.%s = \'%s\'', $rootAlias, $filter, $value));
        }

        return $queryBuilder->getQuery()->getResult();
    }

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return ($resourceClass === AbstractAdvancedRight::class) && $operationName === 'delete';
    }
}
