function createDataset(fields, constraints, sortFields) {
    var dataset = DatasetBuilder.newDataset();
    dataset.addColumn("STATUS");
    dataset.addColumn("MESSAGE");
    dataset.addColumn("PROCESS_INSTANCE_ID");
    dataset.addColumn("RAW_RESPONSE");

    try {
        var params = constraintsToMap(constraints);
        var autorizadorResponsavel = valueOrEmpty(params.autorizador_responsavel || params.autorizadorResponsavel);
        validateRequired(params);

        var payload = {
            targetState: parseInt(params.targetState || "5", 10),
            comment: params.comment || "Envio via portal fornecedor",
            formFields: {
                data_abertura: valueOrEmpty(params.data_abertura),
                emitido_por: valueOrEmpty(params.emitido_por),
                entidade_responsavel: valueOrEmpty(params.entidade_responsavel),
                tipo_cadastro: valueOrEmpty(params.tipo_cadastro),
                emailSolicitante: valueOrEmpty(params.emailSolicitante),
                cpf: valueOrEmpty(params.cpf),
                tipo_documento: valueOrEmpty(params.tipo_documento),
                numero_documento: valueOrEmpty(params.numero_documento),
                valor: valueOrEmpty(params.valor),
                autorizador_responsavel: autorizadorResponsavel,
                justificativa: valueOrEmpty(params.justificativa)
            }
        };

        var clientService = fluigAPI.getAuthorizeClientService();
        var requestData = {
            companyId: getCompanyId(),
            serviceCode: "fluig_rest",
            endpoint: "/process-management/api/v2/processes/FlowEssentials_LancamentodeDocumento/start",
            method: "post",
            timeoutService: "100",
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            },
            options: {
                encoding: "UTF-8",
                mediaType: "application/json",
                useSSL: true
            },
            params: payload
        };

        var vo = clientService.invoke(JSON.stringify(requestData));
        var raw = vo ? String(vo.getResult() || "") : "";
        if (!raw) {
            throw "fluig_rest retornou vazio.";
        }

        var response = parseJsonSafe(raw);
        var processInstanceId = extractProcessInstanceId(response);
        var responseMessage = extractResponseMessage(response);

        if (isErrorResponse(response, raw)) {
            dataset.addRow(["ERROR", responseMessage || "Falha ao iniciar processo.", processInstanceId, raw]);
            return dataset;
        }

        dataset.addRow(["OK", responseMessage || "Solicitação enviada com sucesso.", processInstanceId, raw]);
        return dataset;
    } catch (e) {
        dataset.addRow(["ERROR", errorMessage(e), "", ""]);
        return dataset;
    }
}

function constraintsToMap(constraints) {
    var map = {};
    if (!constraints) {
        return map;
    }

    for (var i = 0; i < constraints.length; i++) {
        var c = constraints[i];
        var fieldName = getFieldNameSafe(c);
        if (!fieldName) {
            continue;
        }
        map[fieldName] = getInitialValueSafe(c);
    }

    return map;
}

function validateRequired(params) {
    var requiredFields = [
        "data_abertura",
        "emitido_por",
        "entidade_responsavel",
        "tipo_cadastro",
        "cpf",
        "numero_documento",
        "justificativa"
    ];

    for (var i = 0; i < requiredFields.length; i++) {
        var fieldName = requiredFields[i];
        if (!valueOrEmpty(params[fieldName])) {
            throw "Campo obrigatório não informado: " + fieldName;
        }
    }

    var autorizador = valueOrEmpty(params.autorizador_responsavel || params.autorizadorResponsavel);
    if (!autorizador) {
        throw "Campo obrigatório não informado: autorizador_responsavel";
    }
}

function extractProcessInstanceId(response) {
    if (!response) return "";
    if (response.processInstanceId) return String(response.processInstanceId);
    if (response.content && response.content.processInstanceId) return String(response.content.processInstanceId);
    if (response.content && response.content.processInstanceid) return String(response.content.processInstanceid);
    if (response.content && response.content.requestNumber) return String(response.content.requestNumber);
    return "";
}

function extractResponseMessage(response) {
    if (!response) return "";
    if (response.message) return String(response.message);
    if (response.detailedMessage) return String(response.detailedMessage);
    if (response.content && response.content.message) return String(response.content.message);
    return "";
}

function isErrorResponse(response, raw) {
    if (!response) return false;
    if (response.code && !extractProcessInstanceId(response)) return true;
    if (response.message && String(response.message).toLowerCase().indexOf("erro") >= 0 && !extractProcessInstanceId(response)) return true;
    if (raw && raw.indexOf("\"code\"") >= 0 && !extractProcessInstanceId(response)) return true;
    return false;
}

function parseJsonSafe(value) {
    try {
        return JSON.parse(value);
    } catch (e) {
        return { raw: value };
    }
}

function getCompanyId() {
    try {
        if (typeof getValue === "function") {
            return String(getValue("WKCompany") || "1");
        }
    } catch (e) {
        // ignore
    }

    return "1";
}

function valueOrEmpty(value) {
    return value == null ? "" : String(value);
}

function errorMessage(e) {
    if (e && e.message) return String(e.message);
    return String(e);
}

function getFieldNameSafe(c) {
    if (!c) return "";
    if (typeof c.getFieldName === "function") return String(c.getFieldName() || "");
    if (c.fieldName !== undefined && c.fieldName !== null) return String(c.fieldName || "");
    return "";
}

function getInitialValueSafe(c) {
    if (!c) return "";
    if (typeof c.getInitialValue === "function") return String(c.getInitialValue() || "");
    if (c.initialValue !== undefined && c.initialValue !== null) return String(c.initialValue || "");
    return "";
}
