package p.studio.workspaces.assets.details.contract;

import p.packer.messages.AssetReference;
import p.packer.messages.assets.OutputFormatCatalog;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

public record RuntimeContractDraft(
        AssetReference assetReference,
        boolean preload,
        OutputFormatCatalog bank,
        Map<String, String> metadataFieldValues) {

    public RuntimeContractDraft {
        Objects.requireNonNull(assetReference, "assetReference");
        bank = Objects.requireNonNullElse(bank, OutputFormatCatalog.UNKNOWN);
        metadataFieldValues = Map.copyOf(Objects.requireNonNull(metadataFieldValues, "metadataFieldValues"));
    }

    public static RuntimeContractDraft fromDetails(AssetWorkspaceAssetDetails details) {
        final Map<String, String> metadataFieldValues = new LinkedHashMap<>();
        details.metadataFields().forEach(field -> metadataFieldValues.put(field.key(), field.value()));
        return new RuntimeContractDraft(
                details.summary().assetReference(),
                details.summary().preload(),
                details.outputFormat(),
                metadataFieldValues);
    }

    public RuntimeContractDraft withPreload(boolean preload) {
        return new RuntimeContractDraft(assetReference, preload, bank, metadataFieldValues);
    }

    public RuntimeContractDraft withMetadataFieldValue(String fieldKey, String value) {
        final Map<String, String> nextValues = new LinkedHashMap<>(metadataFieldValues);
        nextValues.put(fieldKey, Objects.requireNonNullElse(value, ""));
        return new RuntimeContractDraft(assetReference, preload, bank, nextValues);
    }

    public String metadataFieldValue(String fieldKey, String fallback) {
        return metadataFieldValues.getOrDefault(fieldKey, Objects.requireNonNullElse(fallback, ""));
    }
}
