<?php
declare(strict_types=1);

namespace App\Validator\Organization;

use App\Enum\Organization\AddressPostalOrganizationTypeEnum;
use App\Repository\Organization\OrganizationAddressPostalRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use App\Entity\Organization\OrganizationAddressPostal;

/**
 * Classe control qu'une seul et même type d'adresse est autorisé pour les adresses d'organization (à part les "adresses autres")
 */
class OrganizationAddressPostalValidator extends ConstraintValidator
{
    public function __construct(private readonly OrganizationAddressPostalRepository $organizationAddressPostalRepository){}

    public function validate(mixed $value, Constraint $constraint): bool
    {
        /** @var OrganizationAddressPostal $organizationAddressPostal */
        $organizationAddressPostal = $value;

        // si le type est adresse autre, on valide
        if($organizationAddressPostal->getType() === AddressPostalOrganizationTypeEnum::ADDRESS_OTHER()->getValue()) {
            return true;
        }

        $addressesByType = $this->organizationAddressPostalRepository->getByType($organizationAddressPostal->getType(), $organizationAddressPostal->getOrganization());
        //Si le nombre d'adress du type est supérieur à 1, OU si le nombre est égale a 1 ET que l'id de l'adresse n'est pas celui en cours : invalide.
        if(count($addressesByType) > 1 || (count($addressesByType) === 1 && $addressesByType[0]->getId() !== $organizationAddressPostal->getId())){
            $this->context->buildViolation($constraint->payload)
                ->setParameter('{{ type }}', $organizationAddressPostal->getType())
                ->atPath('type')
                ->addViolation();
            return false;
        }
        return true;
    }
}