package com.r35157.nenjim.service.journal.valuetypes;

import java.util.Objects;
import java.util.regex.Pattern;

/** Identifies exactly one Nenjim artifact and its Journal chain. */
public record ArtifactCoordinate(String group, String module, String artifact) {
    private static final Pattern COMPONENT = Pattern.compile("[A-Za-z0-9_.]+");

    public ArtifactCoordinate {
        group = validate("group", group);
        module = validate("module", module);
        artifact = validate("artifact", artifact);
    }

    public static ArtifactCoordinate parse(String value) {
        Objects.requireNonNull(value, "value");
        String[] components = value.split("-", -1);
        if (components.length != 3) {
            throw new IllegalArgumentException(
                    "Artifact coordinate must have the form <GROUP>-<MODULE>-<ARTIFACT>: '" + value + "'");
        }
        return new ArtifactCoordinate(components[0], components[1], components[2]);
    }

    @Override
    public String toString() {
        return group + "-" + module + "-" + artifact;
    }

    private static String validate(String name, String value) {
        Objects.requireNonNull(value, name);
        if (!COMPONENT.matcher(value).matches()) {
            throw new IllegalArgumentException(
                    "Artifact " + name + " must contain only letters, digits, '_' and '.': '" + value + "'");
        }
        return value;
    }
}
