<?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\MainBundle\Entity\NewsItem;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ObjectRepository;
use Symfony\Component\Clock\ClockInterface;

class NewsItemRepository implements ObjectRepository
{
    private readonly EntityRepository $repository;

    public function __construct(EntityManagerInterface $entityManager, private readonly ClockInterface $clock)
    {
        $this->repository = $entityManager->getRepository(NewsItem::class);
    }

    public function createQueryBuilder(string $alias, ?string $indexBy = null): QueryBuilder
    {
        return $this->repository->createQueryBuilder($alias, $indexBy);
    }

    public function find($id)
    {
        return $this->repository->find($id);
    }

    public function findAll()
    {
        return $this->repository->findAll();
    }

    public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null)
    {
        return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
    }

    public function findOneBy(array $criteria)
    {
        return $this->repository->findOneBy($criteria);
    }

    public function getClassName()
    {
        return NewsItem::class;
    }

    private function buildBaseQuery(
        ?string $pattern = null,
    ): QueryBuilder {
        $qb = $this->createQueryBuilder('n');

        $qb->where('n.startDate <= :now');
        $qb->setParameter('now', $this->clock->now());

        if (null !== $pattern && '' !== $pattern) {
            $qb->andWhere($qb->expr()->like('LOWER(UNACCENT(n.title))', 'LOWER(UNACCENT(:pattern))'))
                ->orWhere($qb->expr()->like('LOWER(UNACCENT(n.content))', 'LOWER(UNACCENT(:pattern))'))
                ->setParameter('pattern', '%'.$pattern.'%');
        }

        return $qb;
    }

    public function findAllFilteredBySearchTerm(?string $pattern = null)
    {
        $qb = $this->buildBaseQuery($pattern);
        $qb
            ->addOrderBy('n.startDate', 'DESC')
            ->addOrderBy('n.id', 'DESC');

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

    /**
     * @return list<NewsItem>
     */
    public function findCurrentNews(?int $limit = null, ?int $offset = null): array
    {
        $qb = $this->buildQueryCurrentNews();
        $qb->addOrderBy('n.startDate', 'DESC');

        if (null !== $limit) {
            $qb->setMaxResults($limit);
        }

        if (null !== $offset) {
            $qb->setFirstResult($offset);
        }

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

    public function countAllFilteredBySearchTerm(?string $pattern = null)
    {
        $qb = $this->buildBaseQuery($pattern);

        return $qb
            ->select('COUNT(n)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    public function countCurrentNews()
    {
        return $this->buildQueryCurrentNews()
            ->select('COUNT(n)')
            ->getQuery()
            ->getSingleScalarResult();
    }

    private function buildQueryCurrentNews(): QueryBuilder
    {
        $now = $this->clock->now();

        $qb = $this->createQueryBuilder('n');
        $qb
            ->where(
                $qb->expr()->andX(
                    $qb->expr()->lte('n.startDate', ':now'),
                    $qb->expr()->orX(
                        $qb->expr()->gt('n.endDate', ':now'),
                        $qb->expr()->isNull('n.endDate')
                    )
                )
            )
            ->setParameter('now', $now);

        return $qb;
    }
}
