// Task Team — Pohoda XML Connector — 2026-03-29
// Stormware Pohoda mServer XML API adapter

async function pohodaConnector(app) {

    function buildXML(fn, innerXML) {
        return '<?xml version="1.0" encoding="Windows-1250"?>' +
            '<dat:dataPack xmlns:dat="http://www.stormware.cz/schema/version_2/data.xsd" ' +
            'xmlns:lst="http://www.stormware.cz/schema/version_2/list.xsd" ' +
            'version="2.0" id="req1" ico="" application="TaskTeam">' +
            '<dat:dataPackItem version="2.0" id="item1">' +
            '<lst:' + fn + 'Request version="2.0">' + innerXML + '</lst:' + fn + 'Request>' +
            '</dat:dataPackItem></dat:dataPack>';
    }

    async function pohodaCall(url, username, password, xml) {
        const res = await fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/xml; charset=Windows-1250",
                "STW-Authorization": "Basic " + Buffer.from(username + ":" + password).toString("base64"),
                "STW-Application": "TaskTeam"
            },
            body: xml
        });
        return res.text();
    }

    app.get("/connectors/pohoda/test", async (req) => {
        const { url, username, password } = req.query;
        try {
            const xml = buildXML("listInvoice", "");
            const result = await pohodaCall(url || "http://localhost:58523", username || "Admin", password || "", xml);
            return { status: "ok", response_length: result.length };
        } catch (e) {
            return { status: "error", message: e.message };
        }
    });

    app.post("/connectors/pohoda/sync/invoices", async (req) => {
        const { url, username, password } = req.body;
        const xml = buildXML("listInvoice", "");
        const result = await pohodaCall(url, username, password, xml);
        const invoices = result.match(/<inv:number>(\d+)<\/inv:number>/g) || [];
        return { status: "ok", found: invoices.length };
    });

    app.post("/connectors/pohoda/webhook", async (req) => {
        app.log.info({ body: req.body }, "Pohoda webhook");
        return { status: "received" };
    });
}

module.exports = pohodaConnector;
