<?php


namespace AutoAdmin\Bundle\Content\Resolver;


use AutoAdmin\Bundle\Content\Configuration\ConfigManager;
use AutoAdmin\Bundle\Content\Repository\AbstractContentRepository;
use Doctrine\Persistence\ManagerRegistry;

class ContentResolver
{
    private ManagerRegistry $doctrine;
    private ConfigManager $config;

    public function __construct(ManagerRegistry $doctrine, ConfigManager $config)
    {
        $this->doctrine = $doctrine;
        $this->config = $config;
    }

    public function resolveById(string $contentSlug, $id)
    {
        $repo = $this->getRepoFromSlug($contentSlug);

        return $repo->contentFindOneBy(['_.id' => $id]);
    }

    protected function getRepoFromSlug(string $contentSlug): AbstractContentRepository
    {
        /** @var AbstractContentRepository $repo */
        $repo = $this->doctrine->getRepository($this->resolveClassFromSlug($contentSlug));

        return $repo;
    }

    protected function resolveClassFromSlug($slug): string
    {
        return $this->config->getContentConfigForSlug($slug)['class'];
    }

    public function resolveBySlug(string $contentSlug, $slug)
    {
        $repo = $this->getRepoFromSlug($contentSlug);

        return $repo->contentFindOneBy(['_tr.slug' => $slug]);
    }

    public function resolveBySlugAdmin(string $contentSlug, $slug)
    {
        $repo = $this->getRepoFromSlug($contentSlug);

        return $repo->contentFindOneBy(['_.slugAdmin' => $slug]);
    }
}
