"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSvnSyncTopicHandler = createSvnSyncTopicHandler;
const errors_1 = require("@yinuo-ngm/errors");
const keyOf = (projectId) => `svn:${projectId}`;
function createSvnSyncTopicHandler(deps, getAllClients) {
    return {
        topic: "svn",
        async sub(ctx, msg) {
            const projectId = String(msg?.projectId ?? "").trim();
            if (!projectId) {
                ctx.send({ op: "error", code: errors_1.CoreErrorCodes.PROJECT_ID_REQUIRED, message: "projectId is required", ts: Date.now() });
                return;
            }
            const t = Number(msg?.tail ?? 0) || 0;
            ctx.addSub("svn", keyOf(projectId));
            if (deps.getSvnRuntimeByProjectId) {
                const runtimes = await deps.getSvnRuntimeByProjectId(projectId, t);
                if (runtimes?.length) {
                    runtimes.forEach(runtime => {
                        const m = {
                            op: "svn.event",
                            type: "runtime",
                            payload: runtime,
                            ts: Date.now(),
                        };
                        ctx.send(m);
                    });
                }
            }
        },
        async unsub(ctx, msg) {
            const projectId = String(msg?.projectId ?? "").trim();
            if (!projectId) {
                ctx.send({ op: "error", code: errors_1.CoreErrorCodes.PROJECT_ID_REQUIRED, message: "projectId is required", ts: Date.now() });
                return;
            }
            ctx.delSub("svn", keyOf(projectId));
        },
        pushEvent(type, payload) {
            const m = { op: "svn.event", type, payload, ts: Date.now() };
            for (const c of getAllClients())
                if (c.hasSub("svn", keyOf(payload.projectId)))
                    c.send(m);
        }
    };
}
