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 SearchDatasetNodeParser extends BaseNodeParser {

    private static final String SOURCE_MISSING_MESSAGE = "查询数据节点未选择连接服务";
    private static final String SQL_MISSING_MESSAGE = "查询数据节点未设置 SQL";

    @Override
    protected BaseNode doParse(JSONObject root, JSONObject data, JSONObject tinyflow) {
        if (data == null) {
            throw new BusinessException(SOURCE_MISSING_MESSAGE);
        }
        DatasetRef datasetRef = data.getObject("datasetRef", DatasetRef.class);
        if (datasetRef == null || datasetRef.getSourceId() == null) {
            throw new BusinessException(SOURCE_MISSING_MESSAGE);
        }
        String querySql = data.getString("querySql");
        if (querySql == null || querySql.isBlank()) {
            throw new BusinessException(SQL_MISSING_MESSAGE);
        }
        return new SearchDatasetNode(datasetRef, querySql);
    }

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