<?php

declare(strict_types=1);

namespace App\Administration\Domain\Model\SchoolBranding;

use App\Administration\Domain\Exception\BrandColorInvalideException;

use function hexdec;
use function preg_match;
use function strtoupper;
use function substr;
use function trim;

/**
 * Value Object représentant une couleur de branding (format hexadécimal).
 *
 * Contraintes :
 * - Format #RRGGBB
 * - Exemple: "#3B82F6" (bleu), "#1E40AF" (bleu foncé)
 */
final class BrandColor
{
    private const string PATTERN = '/^#[0-9A-F]{6}$/';

    public function __construct(
        public private(set) string $value {
            set(string $value) {
                $normalized = strtoupper(trim($value));

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

                $this->value = $normalized;
            }
        },
    ) {
    }

    /**
     * Convertit la couleur en composantes RGB.
     *
     * @return array{r: int, g: int, b: int}
     */
    public function toRgb(): array
    {
        return [
            'r' => (int) hexdec(substr($this->value, 1, 2)),
            'g' => (int) hexdec(substr($this->value, 3, 2)),
            'b' => (int) hexdec(substr($this->value, 5, 2)),
        ];
    }

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

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