<?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\Address;
use Chill\MainBundle\Entity\GeographicalUnit;
use Chill\MainBundle\Entity\GeographicalUnit\SimpleGeographicalUnitDTO;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;

final readonly class GeographicalUnitRepository implements GeographicalUnitRepositoryInterface
{
    private EntityRepository $repository;

    public function __construct(EntityManagerInterface $em)
    {
        $this->repository = $em->getRepository($this->getClassName());
    }

    public function countGeographicalUnitContainingAddress(Address $address): int
    {
        $qb = $this->buildQueryGeographicalUnitContainingAddress($address);

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

    public function findGeographicalUnitContainingAddress(Address $address, int $offset = 0, int $limit = 50): array
    {
        $qb = $this->buildQueryGeographicalUnitContainingAddress($address);

        return $qb
            ->select(sprintf('NEW %s(gu.id, gu.unitName, gu.unitRefId, IDENTITY(gu.layer))', SimpleGeographicalUnitDTO::class))
            ->addOrderBy('IDENTITY(gu.layer)')
            ->addOrderBy('gu.unitName')
            ->getQuery()
            ->setFirstResult($offset)
            ->setMaxResults($limit)
            ->getResult();
    }

    private function buildQueryGeographicalUnitContainingAddress(Address $address): QueryBuilder
    {
        $qb = $this->repository
            ->createQueryBuilder('gu')
        ;

        return $qb
            ->select(sprintf('NEW %s(gu.id, gu.unitName, gu.unitRefId, IDENTITY(gu.layer))', SimpleGeographicalUnitDTO::class))
            ->innerJoin(Address::class, 'address', Join::WITH, 'ST_CONTAINS(gu.geom, address.point) = TRUE')
            ->where($qb->expr()->eq('address', ':address'))
            ->setParameter('address', $address)
        ;
    }

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

    public function findSimpleGeographicalUnit(int $id): ?SimpleGeographicalUnitDTO
    {
        $qb = $this->repository
            ->createQueryBuilder('gu');

        return $qb
            ->select(sprintf('NEW %s(gu.id, gu.unitName, gu.unitRefId, IDENTITY(gu.layer))', SimpleGeographicalUnitDTO::class))
            ->where('gu.id = :id')
            ->setParameter('id', $id)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * Will return only partial object, where the @see{GeographicalUnit::geom} property is not loaded.
     *
     * @return array|GeographicalUnit[]
     */
    public function findAll(): array
    {
        return $this->repository
            ->createQueryBuilder('gu')
            ->select(sprintf('NEW %s(gu.id, gu.unitName, gu.unitRefId, IDENTITY(gu.layer))', SimpleGeographicalUnitDTO::class))
            ->addOrderBy('IDENTITY(gu.layer)')
            ->addOrderBy('gu.unitName')
            ->getQuery()
            ->getResult();
    }

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

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

    public function getClassName(): string
    {
        return GeographicalUnit::class;
    }
}
