// auto-split module


    function sleep(ms) {
        return new Promise(r => setTimeout(r, ms));
    }


    async function getJSON(url) {
        const r = await fetch(url, {
            method: "GET",
            headers: {
                "Authorization": "Bearer " + DOCBEE_TOKEN,
                "Accept": "application/json"
            }
        });
        const text = await r.text().catch(() => "-");
        let json = null;
        try {
            json = JSON.parse(text);
        } catch {}
        console.log("[DocBee][GET]", url);
        console.log("[DocBee][RES]", r.status, text.slice(0, 700));
        return {
            ok: r.ok,
            status: r.status,
            json,
            text
        };
    }


async function putJSON(url, body) {
    const r = await fetch(url, {
        method: "PUT",
        headers: {
            "Authorization": "Bearer " + DOCBEE_TOKEN,
            "Content-Type": "application/json; charset=utf-8",
            "Accept": "application/json"
        },
        body: JSON.stringify(body)
    });
    const text = await r.text().catch(() => "-");
    console.log("[DocBee][PUT]", url, body);
    console.log("[DocBee][RES]", r.status, text.slice(0, 700));
    let json = null;
    try {
        json = JSON.parse(text);
    } catch {}
    return {
        ok: r.ok,
        status: r.status,
        json,
        text
    };
}


async function postJSON(url, body) {
    const r = await fetch(url, {
        method: "POST",
        headers: {
            "Authorization": "Bearer " + DOCBEE_TOKEN,
            "Content-Type": "application/json; charset=utf-8",
            "Accept": "application/json"
        },
        body: JSON.stringify(body)
    });
    const text = await r.text().catch(() => "-");
    console.log("[DocBee][POST]", url, body);
    console.log("[DocBee][RES]", r.status, text.slice(0, 700));
    if (r.status === 401) {
        try {
            updateTokenBadge("bad");
        } catch (_) {}
    }
    return {
        ok: r.ok,
        status: r.status,
        text
    };
}


async function restoreTicketStatus(ticketId, prevStatusId) {
    try {
        const maxLoops = 5; // ~30s
        let stable = 0;
        for (let i = 0; i < maxLoops; i++) {
            await sleep(100);
            const tCur = await getJSON(`${DOCBEE_BASEURL}/restApi/v1/ticket/${ticketId}?fields=ticketStatus`);
            const curId = tCur?.json?.ticketStatus ?? null;
            if (curId == null) break;
            if (curId !== prevStatusId) {
                let r = await putJSON(`${DOCBEE_BASEURL}/restApi/v1/ticket/${ticketId}`, {
                    ticketStatus: {
                        id: prevStatusId
                    }
                });
                if (!r.ok) {
                    await putJSON(`${DOCBEE_BASEURL}/restApi/v1/ticket/${ticketId}`, {
                        status: {
                            id: prevStatusId
                        }
                    });
                }
                stable = 0;
            } else {
                stable++;
                if (stable >= 2) break;
            }
        }
    } catch (e) {
        console.warn("[DocBee] restoreTicketStatus failed:", e);
    }
}


async function setTicketStatus(ticketId, statusId) {
    const base = `${DOCBEE_BASEURL}/restApi/v1`;
    const tries = [
        () => putJSON(`${base}/ticket/${ticketId}`, {
            ticketStatus: statusId
        }),
    ];
    let last = null;
    for (let i = 0; i < tries.length; i++) {
        try {
            const r = await tries[i]();
            console.log(`[DocBee][STATUS][try ${i}]`, r?.status, r?.ok);
            if (r && r.ok) return {
                ok: true,
                variant: i,
                status: r.status,
                text: r.text
            };
            last = r;
        } catch (e) {
            console.warn(`[DocBee][STATUS][try ${i}] exception`, e);
            last = {
                ok: false,
                status: 0,
                text: String(e)
            };
        }
    }
    return last || {
        ok: false
    };
}

