<?php

declare(strict_types=1);

namespace NoahVet\Reef\Security\IAM\Finder;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Uid\Uuid;

abstract class AbstractDoctrineResourceFinder implements ResourceFinderEnumeratorInterface, ReverseResourceFinderInterface
{
    /**
     * @param class-string $entityClass
     */
    public function __construct(
        protected string $entityClass,
        protected string $iamPrefix,
        protected EntityManagerInterface $entityManager,
    ) {
    }

    public function enumerate(): \Generator
    {
        $iterable = $this->entityManager->createQueryBuilder()
            ->select('a')
            ->from($this->entityClass, 'a')
            ->getQuery()->toIterable()
        ;

        foreach ($iterable as $entity) {
            yield $entity;
        }
    }

    /**
     * @psalm-suppress QueryBuilderSetParameter
     */
    public function findBySlug(string $slug): mixed
    {
        if (!\str_starts_with($slug, $this->iamPrefix)) {
            return null;
        }

        $id = \str_replace($this->iamPrefix, '', $slug);
        if (Uuid::isValid($id)) {
            $id = Uuid::fromString($id);
        }

        return $this->entityManager->createQueryBuilder()
            ->select('a')
            ->from($this->entityClass, 'a')
            ->where('a.id = :id')
            ->setParameter('id', $id)
            ->getQuery()->getOneOrNullResult()
        ;
    }
}
