package p.packer.messages;

import java.util.Objects;

public record AssetReference(String value) {
    private static final String ASSET_ID_PREFIX = "asset:id:";
    private static final String ASSET_ROOT_PREFIX = "asset:root:";

    public AssetReference {
        value = Objects.requireNonNull(value, "value").trim();
        if (value.isBlank()) {
            throw new IllegalArgumentException("value must not be blank");
        }
    }

    public static AssetReference of(String value) {
        return new AssetReference(value);
    }

    public static AssetReference forAssetId(int assetId) {
        if (assetId <= 0) {
            throw new IllegalArgumentException("assetId must be positive");
        }
        return new AssetReference(ASSET_ID_PREFIX + assetId);
    }

    public static AssetReference forRelativeAssetRoot(String relativeAssetRoot) {
        final String normalized = Objects.requireNonNull(relativeAssetRoot, "relativeAssetRoot").trim();
        if (normalized.isBlank()) {
            throw new IllegalArgumentException("relativeAssetRoot must not be blank");
        }
        return new AssetReference(ASSET_ROOT_PREFIX + normalized);
    }

    public boolean isAssetIdReference() {
        return value.startsWith(ASSET_ID_PREFIX);
    }

    public boolean isAssetRootReference() {
        return value.startsWith(ASSET_ROOT_PREFIX);
    }

    public String rawValue() {
        if (isAssetIdReference()) {
            return value.substring(ASSET_ID_PREFIX.length());
        }
        if (isAssetRootReference()) {
            return value.substring(ASSET_ROOT_PREFIX.length());
        }
        return value;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof AssetReference(String v1))) return false;
        return value.equals(v1);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }
}
