<?php

declare(strict_types=1);

namespace App\Administration\Domain\Model\Subject;

use App\Administration\Domain\Exception\SubjectNameInvalideException;

use function assert;
use function mb_strlen;
use function trim;

/**
 * Value Object représentant le nom d'une matière.
 *
 * Contraintes :
 * - Entre 2 et 100 caractères
 * - Non vide après trim
 */
final class SubjectName
{
    private const int MIN_LENGTH = 2;
    private const int MAX_LENGTH = 100;

    public function __construct(
        /** @var non-empty-string */
        public private(set) string $value {
            set(string $value) {
                $trimmed = trim($value);
                $length = mb_strlen($trimmed);

                if ($length < self::MIN_LENGTH || $length > self::MAX_LENGTH) {
                    throw SubjectNameInvalideException::pourLongueur($value, self::MIN_LENGTH, self::MAX_LENGTH);
                }

                // After validation, $trimmed is guaranteed to be non-empty (MIN_LENGTH >= 2)
                assert($trimmed !== '');
                $this->value = $trimmed;
            }
        },
    ) {
    }

    public function equals(self $other): bool
    {
        return $this->value === $other->value;
    }

    /**
     * @return non-empty-string
     */
    public function __toString(): string
    {
        return $this->value;
    }
}
