<?php

namespace App\Shared\Event\Repository;

use App\Shared\Event\Entity\DomainEventLog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<DomainEventLog> */
class DomainEventLogRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, DomainEventLog::class);
    }

    /**
     * ردیف‌های منتشرنشده‌ای که هنوز سقف تلاش را رد نکرده‌اند.
     *
     * @return DomainEventLog[]
     */
    public function findPending(int $limit = 100): array
    {
        return $this->createQueryBuilder('e')
            ->where('e.publishedAt IS NULL')
            ->andWhere('e.attempts < :max')
            ->setParameter('max', DomainEventLog::MAX_ATTEMPTS)
            ->orderBy('e.occurredAt', 'ASC')
            ->addOrderBy('e.id', 'ASC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    /**
     * @return DomainEventLog[]
     */
    public function search(?string $name, ?string $entityType, ?int $entityId, int $limit = 100): array
    {
        $qb = $this->createQueryBuilder('e')
            ->orderBy('e.occurredAt', 'DESC')
            ->addOrderBy('e.id', 'DESC')
            ->setMaxResults(min($limit, 500));

        if ($name !== null && $name !== '') {
            $qb->andWhere('e.name = :name')->setParameter('name', $name);
        }

        if ($entityType !== null && $entityId !== null) {
            $qb->andWhere('e.entityType = :type')
                ->andWhere('e.entityId = :id')
                ->setParameter('type', $entityType)
                ->setParameter('id', $entityId);
        }

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