function beforeTaskSave(colleagueId, nextSequenceId, userList) {
    try {
        var currentState = parseInt(getValue("WKNumState"), 10);
        var completeTask = String(getValue("WKCompletTask") || "false");
        var nextState = parseInt(String(nextSequenceId || "0"), 10);

        if (completeTask !== "true") return;

        if (currentState === 6) {
            // Fluxo de cancelamento saindo da atividade 6 nao deve disparar template de nota emitida.
            if (nextState === 97) return;
            enviarNotificacaoNotaEmitida();
            return;
        }

        if (currentState === 31) {
            enviarNotificacaoColetaRealizada();
            return;
        }

        if (currentState === 57) {
            // 61 = cancelamento no diagrama.
            if (nextState === 61) return;
            enviarNotificacaoEntregaRealizada();
        }
    } catch (e) {
        log.error("[Transferencia.beforeTaskSave] Erro no beforeTaskSave: " + e);
    }
}

function enviarNotificacaoNotaEmitida() {
    var envio = montarContextoEnvio();
    if (!envio.ok) return;

    var params = buildCommonParams(envio.processNumber, envio.chaveNfe, envio.processLink);
    notifyTemplate("tpl_nota_emitida", envio.destinoEmail, envio.requesterId, params, envio.processNumber, envio.processLink);
}

function enviarNotificacaoColetaRealizada() {
    var envio = montarContextoEnvio();
    if (!envio.ok) return;

    var motoristaColetaNome = safeTrim(hAPI.getCardValue("motoristaColetaNome"));
    var dataColeta = safeTrim(hAPI.getCardValue("dataColeta"));
    var motoristaEntregaNome = safeTrim(hAPI.getCardValue("motoristaEntregaNome"));
    var tipoMotoristaEntrega = safeTrim(hAPI.getCardValue("tipoMotoristaEntrega"));

    if (motoristaEntregaNome === "" && tipoMotoristaEntrega === "mesmo") {
        motoristaEntregaNome = motoristaColetaNome;
    }

    var params = buildCommonParams(envio.processNumber, envio.chaveNfe, envio.processLink);
    params.put("motoristaColetaNome", motoristaColetaNome);
    params.put("dataColeta", dataColeta);
    params.put("motoristaEntregaNome", motoristaEntregaNome);

    notifyTemplate("tpl_coleta_realizada", envio.destinoEmail, envio.requesterId, params, envio.processNumber, envio.processLink);
}

function enviarNotificacaoEntregaRealizada() {
    var envio = montarContextoEnvio();
    if (!envio.ok) return;

    var motoristaEntregaNome = safeTrim(hAPI.getCardValue("motoristaEntregaNome"));
    var dataEntrega = safeTrim(hAPI.getCardValue("dataEntrega"));
    var nomerecebedor = safeTrim(hAPI.getCardValue("nomerecebedor"));

    var params = buildCommonParams(envio.processNumber, envio.chaveNfe, envio.processLink);
    params.put("motoristaEntregaNome", motoristaEntregaNome);
    params.put("dataEntrega", dataEntrega);
    params.put("nomerecebedor", nomerecebedor);

    notifyTemplate("tpl_entrega_realizada", envio.destinoEmail, envio.requesterId, params, envio.processNumber, envio.processLink);
}

function montarContextoEnvio() {
    var requesterId = safeTrim(hAPI.getCardValue("requesterId"));
    var requesterMail = safeTrim(hAPI.getCardValue("requesterMail"));

    if (requesterId === "" && requesterMail !== "") {
        requesterId = findColleagueIdByMail(requesterMail);
    }

    // Prioriza email explicito salvo no formulario; fallback para email do colleague.
    var destinoEmail = requesterMail;
    if (!isValidEmail(destinoEmail)) {
        destinoEmail = resolveEmailByColleagueId(requesterId);
    }

    if (!isValidEmail(destinoEmail)) {
        log.warn("[Transferencia.beforeTaskSave] Email do solicitante invalido. requesterId=" + requesterId + ", requesterMail=[" + requesterMail + "], destinoEmail=[" + destinoEmail + "]");
        return { ok: false };
    }

    var processNumber = safeTrim(getValue("WKNumProces"));
    var chaveNfe = onlyDigits(hAPI.getCardValue("chaveNfe"));
    if (chaveNfe === "") chaveNfe = safeTrim(hAPI.getCardValue("chaveNfe"));
    var processLink = buildProcessLink(processNumber);

    return {
        ok: true,
        requesterId: requesterId,
        destinoEmail: destinoEmail,
        processNumber: processNumber,
        chaveNfe: chaveNfe,
        processLink: processLink
    };
}

function buildCommonParams(processNumber, chaveNfe, processLink) {
    var params = new java.util.HashMap();
    params.put("WKNumProces", processNumber);
    params.put("chaveNfe", chaveNfe);
    params.put("linkSolicitacao", processLink);
    params.put("link", processLink);
    return params;
}

function notifyTemplate(templateCode, destinoEmail, requesterId, params, processNumber, processLink) {
    var NOTIFIER_SENDER_USER = "admin";
    var recipients = new java.util.ArrayList();
    recipients.add(destinoEmail);

    notifier.notify(NOTIFIER_SENDER_USER, templateCode, params, recipients, "text/html");
    log.info("[Transferencia.beforeTaskSave] " + templateCode + " enviado. processo=" + processNumber + ", destino=" + destinoEmail + ", requesterId=" + requesterId + ", link=[" + processLink + "]");
}

function buildProcessLink(processNumber) {
    var BASE_URL_FALLBACK = "https://comerciode188006.fluig.cloudtotvs.com.br";
    var baseUrl = safeTrim(getValue("WKServerURL"));
    var companyId = safeTrim(getValue("WKCompany"));
    if (baseUrl === "") baseUrl = BASE_URL_FALLBACK;
    if (baseUrl.indexOf("http://") !== 0 && baseUrl.indexOf("https://") !== 0) {
        baseUrl = "https://" + baseUrl;
    }
    if (baseUrl.charAt(baseUrl.length - 1) === "/") baseUrl = baseUrl.substring(0, baseUrl.length - 1);
    if (companyId === "") companyId = "1";
    if (baseUrl === "" || safeTrim(processNumber) === "") return "";
    return baseUrl + "/portal/p/" + companyId + "/pageworkflowview?app_ecm_workflowview_detailsProcessInstanceID=" + processNumber;
}

function findColleagueIdByMail(mail) {
    var email = safeTrim(mail);
    if (email === "") return "";

    try {
        var cMail = DatasetFactory.createConstraint("mail", email, email, ConstraintType.MUST);
        var dsColleague = DatasetFactory.getDataset("colleague", null, [cMail], null);
        if (!dsColleague || dsColleague.rowsCount < 1) return "";

        return safeTrim(
            dsColleague.getValue(0, "colleaguePK.colleagueId") ||
            dsColleague.getValue(0, "colleagueId") ||
            dsColleague.getValue(0, "login")
        );
    } catch (e) {
        log.warn("[Transferencia.beforeTaskSave] Falha ao buscar solicitante por mail: " + e);
        return "";
    }
}

function resolveEmailByColleagueId(colleagueId) {
    var id = safeTrim(colleagueId);
    if (id === "") return "";

    try {
        var cActive = DatasetFactory.createConstraint("active", "true", "true", ConstraintType.MUST);

        var cId = DatasetFactory.createConstraint("colleaguePK.colleagueId", id, id, ConstraintType.MUST);
        var byId = DatasetFactory.getDataset("colleague", null, [cId, cActive], null);
        if (byId && byId.rowsCount > 0) {
            return safeTrim(byId.getValue(0, "mail"));
        }

        var cLogin = DatasetFactory.createConstraint("login", id, id, ConstraintType.MUST);
        var byLogin = DatasetFactory.getDataset("colleague", null, [cLogin, cActive], null);
        if (byLogin && byLogin.rowsCount > 0) {
            return safeTrim(byLogin.getValue(0, "mail"));
        }
    } catch (e) {
        log.warn("[Transferencia.beforeTaskSave] Falha ao buscar email do solicitante por colleagueId: " + e);
    }

    return "";
}

function isValidEmail(email) {
    var v = safeTrim(email);
    if (v === "") return false;
    if (/\s/.test(v)) return false;

    var at = v.indexOf("@");
    if (at <= 0 || at !== v.lastIndexOf("@")) return false;

    var dot = v.lastIndexOf(".");
    return dot > at + 1 && dot < (v.length - 1);
}

function safeTrim(value) {
    return String(value == null ? "" : value).trim();
}

function onlyDigits(value) {
    return String(value == null ? "" : value).replace(/\D/g, "");
}
