<?php

declare(strict_types=1);

namespace App\Scolarite\Domain\Exception;

use App\Scolarite\Domain\ValueObject\ClassValidationResult;

use function array_filter;
use function array_map;

use DomainException;

use function implode;

final class DuplicationValidationException extends DomainException
{
    /** @param array<ClassValidationResult> $results */
    private function __construct(
        string $message,
        public readonly array $results,
    ) {
        parent::__construct($message);
    }

    /** @param array<ClassValidationResult> $results */
    public static function withResults(array $results): self
    {
        $failures = array_filter($results, static fn (ClassValidationResult $r): bool => !$r->valid);
        $messages = array_map(
            static fn (ClassValidationResult $r): string => "Classe {$r->classId} : {$r->error}",
            $failures,
        );

        return new self(
            'Validation échouée pour certaines classes : ' . implode('; ', $messages),
            $results,
        );
    }
}
