package dev.sonpx.loyalty.mcp.enums;

import java.lang.reflect.Method;
import java.util.Optional;

public final class CodeEnumLookup {

    private CodeEnumLookup() {}

    public static <T extends Enum> T resolve(String source, Class<T> targetType) {
        if (source == null || source.isBlank()) {
            return null;
        }

        String normalized = source.trim();
        for (T constant : targetType.getEnumConstants()) {
            if (constant.name().equalsIgnoreCase(normalized)
                    || codeOf(constant).map(code -> code.equalsIgnoreCase(normalized)).orElse(false)) {
                return constant;
            }
        }

        throw new IllegalArgumentException("Unsupported " + targetType.getSimpleName() + " value: " + source);
    }

    public static String codeOfEnum(Enum<?> constant) {
        return codeOf(constant).orElseGet(constant::name);
    }

    private static Optional<String> codeOf(Object constant) {
        if (constant instanceof EnumBase enumBase) {
            return Optional.ofNullable(enumBase.getCode());
        }

        try {
            Method getCode = constant.getClass().getMethod("getCode");
            Object code = getCode.invoke(constant);
            return code instanceof String value ? Optional.of(value) : Optional.empty();
        } catch (ReflectiveOperationException ex) {
            return Optional.empty();
        }
    }
}
