<?php

namespace App\ClinicService\Repository;

use App\ClinicService\Entity\ServiceItem;
use App\ClinicService\Entity\ServiceItemAuditLog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class ServiceItemAuditLogRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ServiceItemAuditLog::class);
    }

    public function save(ServiceItemAuditLog $log, bool $flush = true): void
    {
        $this->getEntityManager()->persist($log);
        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }

    public function flush(): void
    {
        $this->getEntityManager()->flush();
    }

    /** @return ServiceItemAuditLog[] تازه‌ترین رویداد اول. */
    public function findByItem(ServiceItem $item, int $limit = 100): array
    {
        return $this->createQueryBuilder('l')
            ->where('l.serviceItem = :item')
            ->setParameter('item', $item)
            ->orderBy('l.createdAt', 'DESC')
            ->addOrderBy('l.id', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }
}
