<?php

namespace AutoAdmin\Bundle\Content\Repository;

use AutoAdmin\Bundle\Content\Entity\Log;
use DateTime;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method Log|null find($id, $lockMode = null, $lockVersion = null)
 * @method Log|null findOneBy(array $criteria, array $orderBy = null)
 * @method Log[]    findAll()
 * @method Log[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LogRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Log::class);
    }

    /**
     * Find one less than X minutes by entity and type
     * @param string $entity
     * @param string $type
     * @param int|null $lessThan
     */
    public function findLessThan(string $entity, string $type, ?int $lessThan = 10)
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.entity = :entity')
            ->setParameter('entity', $entity)
            ->andWhere('l.type = :type')
            ->setParameter('type', $type)
            ->andWhere('l.createdAt >= :lessThan')
            ->setParameter('lessThan', new DateTime('-'.$lessThan.' minutes'))
            ->getQuery()
            ->getResult()
        ;
    }

    public function findBefore(DateTime $before, int $limit = 100000)
    {
        $qb = $this->createQueryBuilder('l');
        $qb->where('l.createdAt < :before');
        $qb->setParameter('before', $before);
        $qb->setMaxResults($limit);

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