<?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>
 */
final 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 list<Permission> */
    public function findAll(): array
    {
        return array_values($this->findBy([]));
    }

    /** @return list<string> */
    public function findAllCodes(): array
    {
        /** @var list<array{code: string}> $rows */
        $rows = $this->createQueryBuilder('p')->select('p.code')->getQuery()->getArrayResult();

        return array_map(static fn (array $r): string => $r['code'], $rows);
    }

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