<?php

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,
                \json_encode(
                    self::cases(),
                    \JSON_THROW_ON_ERROR,
                ),
            ),
        );
    }

    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,
                \json_encode(
                    self::cases(),
                    \JSON_THROW_ON_ERROR,
                ),
            ),
        );
    }

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

        return true;
    }
}
