package tech.easyflow.ai.node;

import com.alibaba.fastjson.JSONObject;
import com.easyagents.flow.core.node.BaseNode;
import com.easyagents.flow.core.parser.BaseNodeParser;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.datacenter.execution.model.DatasetRef;

public class SaveDatasetNodeParser extends BaseNodeParser {

    private static final String EXPIRED_MESSAGE = "写入数据节点配置已过期，请重新选择已接入表";

    @Override
    protected BaseNode doParse(JSONObject root, JSONObject data, JSONObject tinyflow) {
        if (data == null) {
            throw new BusinessException(EXPIRED_MESSAGE);
        }
        if (hasLegacyFields(data)) {
            throw new BusinessException(EXPIRED_MESSAGE);
        }
        DatasetRef datasetRef = data.getObject("datasetRef", DatasetRef.class);
        if (datasetRef == null || datasetRef.getTableId() == null) {
            throw new BusinessException(EXPIRED_MESSAGE);
        }
        return new SaveDatasetNode(datasetRef);
    }

    public String getNodeName() {
        return "save-dataset-node";
    }

    private boolean hasLegacyFields(JSONObject data) {
        if (data == null) {
            return false;
        }
        return data.containsKey("tableId")
                || data.containsKey("sourceId")
                || data.containsKey("catalogId")
                || data.containsKey("versionId");
    }
}
