<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\Helper;

trait EnumUtility
{
    public static function fromName(string $name): mixed
    {
        foreach (self::cases() as $case) {
            if ($name === $case->name) {
                return $case;
            }
        }

        throw new \ValueError(message: $name . ' is not a valid case for enum ' . self::class);
    }

    public static function fromValue(mixed $value): mixed
    {
        foreach (self::cases() as $case) {
            if ($value === $case->value) {
                return $case;
            }
        }

        throw new \ValueError(message: $value . ' is not a valid case for enum ' . self::class);
    }

    public static function fromJsonValue(mixed $value, string $offsetName): mixed
    {
        foreach (self::cases() as $case) {
            /** @var mixed $caseValue */
            $caseValue = $case->value;
            if (\is_string($caseValue) === false) {
                continue;
            }
            try {
                /** @var mixed $caseValues */
                $caseValues = \json_decode(
                    $caseValue,
                    false,
                    512,
                    JSON_THROW_ON_ERROR
                );
            } catch (\JsonException) {
                throw new \ValueError(
                    message: 'Invalid JSON format in enum case ' . $case->name . ' for enum ' . self::class
                );
            }
            if (\is_object($caseValues) && ($caseValues->$offsetName ?? null) === $value) {
                return $caseValues;
            }
        }

        return null;
    }
}
