<?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\PersonBundle\Repository\Identifier;

use Chill\PersonBundle\Entity\Identifier\PersonIdentifier;
use Chill\PersonBundle\Entity\Identifier\PersonIdentifierDefinition;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierManagerInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class PersonIdentifierRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry, private readonly PersonIdentifierManagerInterface $personIdentifierManager)
    {
        parent::__construct($registry, PersonIdentifier::class);
    }

    public function findByDefinitionAndCanonical(PersonIdentifierDefinition $definition, array|string $valueOrCanonical): array
    {
        return $this->createQueryBuilder('p')
            ->where('p.definition = :definition')
            ->andWhere('p.canonical = :canonical')
            ->setParameter('definition', $definition)
            ->setParameter(
                'canonical',
                is_string($valueOrCanonical) ?
                    $valueOrCanonical :
                    $this->personIdentifierManager->buildWorkerByPersonIdentifierDefinition($definition)->canonicalizeValue($valueOrCanonical),
            )
            ->getQuery()
            ->getResult();
    }
}
