<?php

namespace AutoAdmin\Bundle\BrickBuilder\Helper;

use AutoAdmin\Bundle\Admin\Configuration\ConfigManager;
use AutoAdmin\Bundle\BrickBuilder\Entity\Brick;
use AutoAdmin\Bundle\Content\Entity\Site;
use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Doctrine\ORM\EntityManagerInterface;

class BrickResolver
{
    public function __construct(
        protected EntityManagerInterface $em,
        protected ConfigManager $cfgManager,
        protected SiteContextHelper $contextHelper,
    ) {
    }

    public function resolve(int $brickId)
    {
        $brickRepo = $this->em->getRepository(Brick::class);

        while (($brick = $brickRepo->find($brickId)) && ($parent = $brick->getParent())) {
            $brickId = $parent->getId();
        }

        if (empty($brick)) {
            return null;
        }

        $entities = $this->cfgManager->getConfig('entities');

        $siteRepo = $this->em->getRepository(Site::class);
        foreach ($siteRepo->findBy(['enabled' => true]) as $site) {
            $siteConfigs = $this->contextHelper->getSiteLocalizedDomains($site);
            foreach ($siteConfigs as $siteConfig) {
                $this->contextHelper->loadSiteConfig($siteConfig);

                foreach ($entities as $class => $entityConfig) {
                    $prop = $this->getBrickProperty($class);
                    if (!empty($prop)) {
                        $propClass = $prop->getDeclaringClass()->getName();
                        $trRefl = new \ReflectionClass($propClass);

                        $repo = $this->em->getRepository($class);
                        if ($propClass !== $class && $trRefl->isSubclassOf(TranslationInterface::class)) {
                            $where = ['_tr.brick' => $brick];
                        } else {
                            $where = ['_.brick' => $brick];
                        }

                        if ($parentContent = $repo->contentFindOneBy($where)) {
                            return $parentContent;
                        }
                    }
                }

            }
        }

        return null;
    }

    protected function getBrickProperty(string $entityClass): ?\ReflectionProperty
    {
        $prop = null;
        $refl = new \ReflectionClass($entityClass);
        try {
            $prop = $refl->getProperty('brick');
        } catch (\ReflectionException $e) {
        }

        if (empty($prop)) {
            $translationClass = $entityClass.'Translation';
            if (class_exists($translationClass)) {
                $refl = new \ReflectionClass($translationClass);
                try {
                    $prop = $refl->getProperty('brick');
                } catch (\ReflectionException $e) {
                }
            }
        }

        return $prop;
    }
}