<?php

declare(strict_types=1);

namespace App\Domain\Common\ValueObject;

final readonly class RGBColor
{
    private function __construct(
        public int $red,
        public int $green,
        public int $blue
    ) {
        foreach ([$red, $green, $blue,
        ] as $value) {
            if ($value < 0 || $value > 255) {
                throw new \InvalidArgumentException(
                    sprintf(
                        'RGB-Farbwert (%d, %d, %d) muss zwischen 0 und 255 liegen.',
                        $red,
                        $green,
                        $blue
                    )
                );
            }
        }
    }

    public static function fromHex(string $hex): self
    {
        $red = hexdec(substr($hex, 0, 2));
        $green = hexdec(substr($hex, 2, 2));
        $blue = hexdec(substr($hex, 4, 2));

        return new self($red, $green, $blue);
    }

    public static function fromRgb(int $red, int $green, int $blue): self
    {
        return new self($red, $green, $blue);
    }

    public function toHex(): string
    {
        return sprintf('#%02x%02x%02x', $this->red, $this->green, $this->blue);
    }

    public function toRgb(): string
    {
        return sprintf('rgb(%d, %d, %d)', $this->red, $this->green, $this->blue);
    }
}
