function servicetask15(attempt, message) {
    var payload = buildSe2010Payload();
    appendDebugSe2010("servicetask15: payload=" + safeStringify(payload));

    var response = invokeSe2010(payload);
    appendDebugSe2010("servicetask15: status=" + response.httpStatus + " body=" + response.raw);

    if (!response.success) {
        throw "Falha ao enviar dados para Protheus SE2010. Status HTTP: " + response.httpStatus + ".";
    }
}

function buildSe2010Payload() {
    var payload = {
        FILIAL: requiredCard("FILIAL"),
        PREFIXO: requiredCard("PREFIXO"),
        NUMERO: requiredCard("NUMERO"),
        PARCELA: requiredCard("PARCELA"),
        TIPO: requiredCard("TIPO"),
        NATUREZA: requiredCard("NATUREZA"),
        COD_FORN: requiredCard("COD_FORN"),
        LOJA: requiredCard("LOJA"),
        EMISSAO: normalizeDate(requiredCard("EMISSAO"), "EMISSAO"),
        VENCIMENTO: normalizeDate(requiredCard("VENCIMENTO"), "VENCIMENTO"),
        VENC_REAL: normalizeDate(requiredCard("VENC_REAL"), "VENC_REAL"),
        VALOR: parseMoney(requiredCard("VALORtotal", "VALOR")),
        HISTORICO: requiredCard("HISTORICO"),
        CODIGO_BARRAS: card("CODIGO_BARRAS"),
        CENTRO_CUSTO: requiredCard("CENTRO_CUSTO")
    };

    return payload;
}

function invokeSe2010(payload) {
    var serviceCode = card("service_code_se2010") || "protheus_teste";
    var endpoint = card("endpoint_se2010") || "https://comerciode186920.protheus.cloudtotvs.com.br:4050/rest/uf_se2010";

    var requestData = {
        companyId: getCompanyIdSafe(),
        serviceCode: serviceCode,
        endpoint: endpoint,
        method: "post",
        timeoutService: "120",
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        },
        options: {
            encoding: "UTF-8",
            mediaType: "application/json",
            useSSL: true
        },
        params: payload
    };

    var clientService = fluigAPI.getAuthorizeClientService();
    var vo = clientService.invoke(JSON.stringify(requestData));
    var raw = vo ? String(vo.getResult() || "") : "";

    if (!raw) {
        throw "Resposta vazia da API SE2010.";
    }

    var httpStatus = getHttpStatus(vo);
    var parsed = parseJsonSafe(raw);
    var success = httpStatus >= 200 && httpStatus < 300;

    if (parsed && parsed.success === false) {
        success = false;
    }

    return {
        success: success,
        httpStatus: httpStatus,
        raw: raw,
        parsed: parsed
    };
}

function requiredCard() {
    var value = "";

    for (var i = 0; i < arguments.length; i++) {
        value = card(arguments[i]);
        if (value) {
            break;
        }
    }

    if (!value) {
        throw "Campo obrigatorio nao informado para envio Protheus: " + arguments[0];
    }

    return value;
}

function card(name) {
    return ((hAPI.getCardValue(name) || "") + "").replace(/^\s+|\s+$/g, "");
}

function normalizeDate(value, fieldName) {
    var digits = (value || "").replace(/\D/g, "");
    if (digits.length !== 8) {
        throw "Data invalida no campo " + fieldName + ". Informe no formato YYYYMMDD.";
    }
    return digits;
}

function parseMoney(value) {
    var raw = (value || "").toString().replace(/\s/g, "");
    if (!raw) {
        return 0;
    }

    if (raw.indexOf(",") >= 0) {
        raw = raw.replace(/\./g, "").replace(",", ".");
    } else {
        var dotCount = (raw.match(/\./g) || []).length;
        if (dotCount > 1) {
            raw = raw.replace(/\./g, "");
        }
    }

    var parsed = parseFloat(raw);
    if (isNaN(parsed)) {
        throw "Valor invalido para envio Protheus: " + value;
    }

    return parseFloat(parsed.toFixed(2));
}

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

function getHttpStatus(vo) {
    try {
        var status = parseInt(String(vo.getHttpStatusResult() || "0"), 10);
        if (!isNaN(status) && status > 0) {
            return status;
        }
    } catch (e) {
        // ignore
    }

    return 200;
}

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

function safeStringify(value) {
    try {
        return JSON.stringify(value);
    } catch (e) {
        return String(value);
    }
}

function appendDebugSe2010(message) {
    try {
        var prefix = "[SE2010] ";
        var atual = (hAPI.getCardValue("debug_publicacao") || "") + "";
        var linha = prefix + message;
        hAPI.setCardValue("debug_publicacao", atual ? (atual + "\n" + linha) : linha);
    } catch (e) {
        log.warn("appendDebugSe2010 falhou: " + e);
    }
}
