<?php

namespace AutoAdmin\Bundle\Admin\Helper;

use AutoAdmin\Bundle\Admin\Router\AdminRouter;
use AutoAdmin\Bundle\Content\Repository\AbstractContentRepository;
use AutoAdmin\Bundle\Core\Helper\DoctrineHelper;
use Doctrine\ORM\EntityManagerInterface;

class EntityPrevNextHelper
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private AdminRouter $adminRouter,
    ) {
    }

    private function getNearbyEntity($entity, $direction)
    {
        $class = get_class($entity);
        $class = DoctrineHelper::removeProxyPrefix($class);
        if ($metadata = $this->entityManager->getClassMetadata($class)) {
            $class = $metadata->getName();
        }

        $repository = $this->entityManager->getRepository($class);

        $repoRefl = new \ReflectionClass($repository);

        if ($repoRefl->isSubclassOf(AbstractContentRepository::class)) {
            $qb = $repository->createContentQueryBuilder();
        } else {
            $qb = $repository->createQueryBuilder('_');
        }

        $qb->andWhere('_.id '.($direction === 'next' ? '>' : '<').' :id');
        $qb->setParameter('id', $entity->getId());
        $qb->orderBy('_.id', $direction === 'next' ? 'ASC' : 'DESC');
        $qb->setMaxResults(1);

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

    public function getPrevNextLinks($entity): array
    {
        $prevEntity = $this->getNearbyEntity($entity, 'prev');
        $nextEntity = $this->getNearbyEntity($entity, 'next');

        if ($prevEntity) {
            $adminPrevEntityUrl = $this->adminRouter->generate($prevEntity, 'update');
        }

        if ($nextEntity) {
            $adminNextEntityUrl = $this->adminRouter->generate($nextEntity, 'update');
        }

        return [
            'prev' => $adminPrevEntityUrl ?? null,
            'next' => $adminNextEntityUrl ?? null,
        ];
    }
}
