package click.kamil.springstatemachineexporter.exporter;

/**
 * Builds SVG/HTML transition link keys ({@code Source__Event}) using the same formatting rules as
 * {@link PlantUml} embedded identifiers and the HTML explorer {@code buildLinkKey} helper.
 */
public final class TransitionLinkKey {

    private TransitionLinkKey() {
    }

    public static String build(String sourceStateIdentifier, String eventIdentifier) {
        return build(sourceStateIdentifier, eventIdentifier, EnumFormat.fn, EnumFormat.fn);
    }

    public static String build(
            String sourceStateIdentifier,
            String eventIdentifier,
            EnumFormat stateFormat,
            EnumFormat eventFormat) {
        if (eventIdentifier == null || eventIdentifier.isBlank()) {
            return "";
        }
        String formattedEvent = formatIdentifier(eventIdentifier, eventFormat);
        if (sourceStateIdentifier == null || sourceStateIdentifier.isBlank()) {
            return "__" + normalize(formattedEvent);
        }
        return normalize(formatIdentifier(sourceStateIdentifier, stateFormat))
                + "__"
                + normalize(formattedEvent);
    }

    static String formatIdentifier(String identifier, EnumFormat format) {
        if (identifier == null || identifier.isBlank()) {
            return "";
        }
        return switch (format) {
            case fqn -> identifier;
            case sn -> {
                int lastDot = identifier.lastIndexOf('.');
                yield lastDot >= 0 ? identifier.substring(lastDot + 1) : identifier;
            }
            case fn -> {
                int lastDot = identifier.lastIndexOf('.');
                if (lastDot <= 0) {
                    yield identifier;
                }
                int prevDot = identifier.lastIndexOf('.', lastDot - 1);
                yield prevDot > 0 ? identifier.substring(prevDot + 1) : identifier;
            }
        };
    }

    static String normalize(String value) {
        if (value == null || value.isBlank()) {
            return "";
        }
        return value.replaceAll("[^a-zA-Z0-9]", "_");
    }
}
