<?php

declare(strict_types=1);

namespace App\Module\Core\Infrastructure\Doctrine;

use App\Module\Core\Domain\Entity\Permission;
use App\Module\Core\Domain\Repository\PermissionRepositoryInterface;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<Permission>
 */
class DoctrinePermissionRepository extends ServiceEntityRepository implements PermissionRepositoryInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Permission::class);
    }

    public function findById(int $id): ?Permission
    {
        return $this->find($id);
    }

    public function findByCode(string $code): ?Permission
    {
        return $this->findOneBy(['code' => $code]);
    }

    /**
     * @return array<int, Permission>
     */
    public function findAll(): array
    {
        return parent::findAll();
    }

    /**
     * @return array<int, string>
     */
    public function findAllCodes(): array
    {
        // Requete legere : on ne selectionne que la colonne code (pas d'hydratation
        // d'entites Permission) car findAllCodes() est appelee par la commande de
        // sync et le futur voter qui n'ont besoin que des chaines.
        $rows = $this->createQueryBuilder('p')
            ->select('p.code')
            ->getQuery()
            ->getArrayResult()
        ;

        return array_column($rows, 'code');
    }

    public function save(Permission $permission): void
    {
        $this->getEntityManager()->persist($permission);
        $this->getEntityManager()->flush();
    }
}
