<?php

declare(strict_types=1);

namespace App\Administration\Domain\Model\Subject;

use App\Administration\Domain\Exception\SubjectColorInvalideException;

use function assert;
use function preg_match;
use function strtoupper;
use function trim;

/**
 * Value Object représentant la couleur d'une matière (format hexadécimal).
 *
 * Contraintes :
 * - Format #RRGGBB
 * - Exemple: "#3B82F6" (bleu), "#EF4444" (rouge)
 */
final class SubjectColor
{
    private const string PATTERN = '/^#[0-9A-F]{6}$/';

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

                if (preg_match(self::PATTERN, $normalized) !== 1) {
                    throw SubjectColorInvalideException::pourFormat($value);
                }

                // After validation, $normalized is guaranteed to be non-empty (#RRGGBB = 7 chars)
                assert($normalized !== '');
                $this->value = $normalized;
            }
        },
    ) {
    }

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

    public function __toString(): string
    {
        return $this->value;
    }
}
