<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Validator\Constraints\Relationship;

use Chill\PersonBundle\Entity\Relationships\Relationship;
use Chill\PersonBundle\Repository\Relationships\RelationshipRepository;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

class RelationshipNoDuplicateValidator extends ConstraintValidator
{
    public function __construct(private readonly RelationshipRepository $relationshipRepository) {}

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

        if (!$value instanceof Relationship) {
            throw new UnexpectedValueException($value, Relationship::class);
        }

        $fromPerson = $value->getFromPerson();
        $toPerson = $value->getToPerson();

        $relationships = $this->relationshipRepository->findBy([
            'fromPerson' => [$fromPerson, $toPerson],
            'toPerson' => [$fromPerson, $toPerson],
        ]);

        foreach ($relationships as $r) {
            if (spl_object_hash($r) !== spl_object_hash($value)
                and (
                    ($r->getFromPerson() === $fromPerson and $r->getToPerson() === $toPerson)
                    || ($r->getFromPerson() === $toPerson and $r->getToPerson() === $fromPerson)
                )
            ) {
                $this->context->buildViolation($constraint->message)
                    ->addViolation();
            }
        }
    }
}
