package fr.bglands.client.protocol;

import java.util.Objects;
import java.util.UUID;

public record UiAction(String instanceId, String controlId, String token, String requestId) {
    public UiAction {
        requireUuid(instanceId, "instanceId");
        requireText(controlId, "controlId", 1, 96);
        requireUuid(token, "token");
        requireUuid(requestId, "requestId");
    }

    public static UiAction create(String instanceId, String controlId, String token) {
        return new UiAction(instanceId, controlId, token, UUID.randomUUID().toString());
    }

    private static void requireUuid(String value, String field) {
        Objects.requireNonNull(value, field);
        try {
            UUID.fromString(value);
        } catch (IllegalArgumentException exception) {
            throw new IllegalArgumentException(field + " must be a UUID", exception);
        }
    }

    private static void requireText(String value, String field, int min, int max) {
        Objects.requireNonNull(value, field);
        if (value.length() < min || value.length() > max) {
            throw new IllegalArgumentException(field + " length must be in [" + min + ", " + max + "]");
        }
    }
}
