<?php

namespace App\Validator\Constraints;

use App\Dto\Input\DeployImageInput;
use App\Dto\Output\ClientOutput;
use App\Entity\Client;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;

class ClientsHaveSamePartitionCountValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint): void
    {
        if (!$value instanceof DeployImageInput) {
            return;
        }

        if (isset($value->clients) && is_array($value->clients)) {
            $partitionCounts = [];
            foreach ($value->clients as $client) {
                $partitionCount = $client->getEntity()->getPartitions()->count();
                $partitionCounts[(string) $client->getEntity()->getIp()] = $partitionCount;
            }

            if (count(array_unique($partitionCounts)) > 1) {
                $errorDetails = [];
                foreach ($partitionCounts as $clientIp => $partitionCount) {
                    $errorDetails[] = "Cliente $clientIp tiene $partitionCount particiones.";
                }

                $detailedMessage = implode(" ", $errorDetails);

                $this->context->buildViolation($constraint->message . ' Detalles: ' . $detailedMessage)
                    ->addViolation();
            }
        }
    }
}