<?php

namespace App\Validator\Constraints;

use App\Dto\Input\RemoteCalendarRuleInput;
use App\Entity\RemoteCalendarRule;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class RemoteCalendarRuleUniqueValidator extends ConstraintValidator
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly RequestStack $requestStack
    )
    {
    }

    public function validate(mixed $value, Constraint $constraint): void
    {
        $request = $this->requestStack->getCurrentRequest();

        if (!$value instanceof RemoteCalendarRuleInput) {
            return;
        }

        if ($value->isRemoteAvailable) {
            return;
        }

        if ($request && $request->getMethod() !== 'POST') {
            return;
        }

        $isRemoteAvailable = $this->entityManager->getRepository(RemoteCalendarRule::class)
            ->findOneBy([
                'remoteCalendar' => $value->remoteCalendar->getEntity(),
                'isRemoteAvailable' => false,
            ]);

        if ($isRemoteAvailable) {
            $this->context->buildViolation($constraint->message)->addViolation();
        }

    }
}