<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Repository;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Repository\AssociatedEntityToStoredObjectInterface;
use Chill\MainBundle\Entity\ExportGeneration;
use Chill\MainBundle\Entity\SavedExport;
use Chill\MainBundle\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<ExportGeneration>
 *
 * @implements AssociatedEntityToStoredObjectInterface<ExportGeneration>
 */
class ExportGenerationRepository extends ServiceEntityRepository implements AssociatedEntityToStoredObjectInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ExportGeneration::class);
    }

    public function findAssociatedEntityToStoredObject(StoredObject $storedObject): ?ExportGeneration
    {
        return $this->createQueryBuilder('e')
            ->where('e.storedObject = :storedObject')
            ->setParameter('storedObject', $storedObject)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * @return list<ExportGeneration>
     */
    public function findExportGenerationByAliasAndUser(string $alias, User $user, int $limit = 100, int $offset = 0): array
    {
        return $this->createQueryBuilder('e')
            ->where('e.createdBy = :user')
            ->andWhere('e.exportAlias LIKE :alias')
            ->orderBy('e.createdAt', 'DESC')
            ->setParameter('user', $user)
            ->setParameter('alias', $alias)
            ->setFirstResult($offset)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    /**
     * @return list<ExportGeneration>
     */
    public function findExportGenerationBySavedExportAndUser(SavedExport $savedExport, User $user, int $limit = 100, int $offset = 0): array
    {
        return $this->createQueryBuilder('e')
            ->where('e.createdBy = :user')
            ->andWhere('e.savedExport = :savedExport')
            ->orderBy('e.createdAt', 'DESC')
            ->setParameter('user', $user)
            ->setParameter('savedExport', $savedExport)
            ->setFirstResult($offset)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function findExpiredExportGeneration(\DateTimeImmutable $atDate): iterable
    {
        return $this->createQueryBuilder('e')
            ->where('e.deleteAt < :atDate')
            ->setParameter('atDate', $atDate)
            ->getQuery()
            ->toIterable();
    }
}
