<?php

declare(strict_types=1);

namespace NoahVet\Reef\Domain\Common;

trait EnumTrait
{
    public static function getEnumFromName(string $name): object
    {
        return (new \ReflectionEnumBackedCase(self::class, $name))->getValue();
    }

    public static function getEnumFromValue(int|string $value): object
    {
        return self::from($value);
    }

    public static function getNameFromValue(int|string $value): string
    {
        if (null !== self::tryFrom($value)) {
            return self::from($value)->name;
        }

        throw new \ValueError(
            \sprintf(
                'The enum value %s doesn\'t exist. The supported enum values are %s.',
                $value,
                (string) \json_encode(
                    self::cases(),
                ),
            ),
        );
    }

    public static function getValueFromName(string $name): string|int
    {
        foreach (self::cases() as $case) {
            if ($case->name === $name) {
                return $case->value;
            }
        }

        throw new \ValueError(
            \sprintf(
                'The enum name %s doesn\'t exist. The supported enum names are %s.',
                $name,
                (string)
                    \json_encode(
                        self::cases(),
                    ),
            ),
        );
    }

    public static function hasName(mixed $name): bool
    {
        if (empty(\array_filter(self::cases(), fn ($case): bool => $case->name === $name))) {
            return false;
        }

        return true;
    }
}
