<?php

namespace AutoAdmin\Bundle\Content\Validator;

use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use AutoAdmin\Bundle\Content\Repository\AbstractContentRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use function is_string;

/** @internal */
class UniqueSlugValidator extends ConstraintValidator
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
    )
    {
    }

    public function validate(mixed $value, Constraint $constraint): void
    {
        if (!$constraint instanceof UniqueSlug) {
            throw new UnexpectedTypeException($constraint, UniqueSlug::class);
        }

        if (null === $value || '' === $value) {
            return;
        }

        if (!is_string($value)) {
            throw new UnexpectedValueException($value, 'string');
        }

        $entity = $this->context->getObject();
        $propertyName = $this->context->getPropertyName();
        $repository = $this->getRepository($entity);

        if ($repository instanceof AbstractContentRepository) {
            if ($entity instanceof TranslationInterface) {
                $alias = '_tr';
                $site = $entity->getTranslatable()->getSite();
                $mainEntityId = $entity->getTranslatable()->getId();
            } else {
                $alias = '_';
                $site = $entity->getSite();
                $mainEntityId = $entity->getId();
            }

            $slugs = $repository->contentFindBy([
                $alias . '.' . $propertyName => $value,
                '_.site' => $site
            ]);

            $slugs = array_filter($slugs, fn($e) => $e->getId() !== $mainEntityId);

            if (empty($slugs)) {
                return;
            }
        }

        $this->context->buildViolation($constraint->message)
            ->setParameter('{{ property }}', $propertyName)
            ->setParameter('{{ value }}', $value)
            ->addViolation();
    }

    private function getRepository($entity): EntityRepository
    {
        if ($entity instanceof TranslationInterface) {
            return $this->entityManager->getRepository($entity->getTranslatable()::class);
        }

        return $this->entityManager->getRepository($entity::class);
    }
}
