"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNginxTopicHandler = createNginxTopicHandler;
const errors_1 = require("@yinuo-ngm/errors");
function createNginxTopicHandler(deps, getAllClients) {
    const { logService } = deps;
    const onLog = (entry) => {
        const msg = {
            op: "nginx.log.append",
            logType: entry.type,
            line: entry.line,
            ts: entry.timestamp
        };
        for (const client of getAllClients()) {
            if (client.hasSub("nginx", `nginx:${entry.type}`)) {
                client.send(msg);
            }
        }
    };
    logService.on("log", onLog);
    return {
        topic: "nginx",
        async sub(ctx, msg) {
            const logType = msg.logType;
            if (!logType || (logType !== "error" && logType !== "access")) {
                ctx.send({
                    op: "error",
                    code: errors_1.GlobalErrorCodes.BAD_MSG,
                    message: "logType must be 'error' or 'access'",
                    ts: Date.now()
                });
                return;
            }
            const subKey = `nginx:${logType}`;
            ctx.addSub("nginx", subKey);
            logService.startWatching(logType);
            const tail = Math.max(0, Number(msg.tail ?? 0));
            if (tail > 0) {
                const lines = await logService.readLogTail(logType, tail);
                const response = {
                    op: "nginx.log.tail",
                    logType,
                    lines,
                    ts: Date.now()
                };
                ctx.send(response);
            }
        },
        unsub(ctx, msg) {
            const logType = msg.logType;
            if (logType) {
                ctx.delSub("nginx", `nginx:${logType}`);
            }
            else {
                ctx.delSub("nginx", "nginx:error");
                ctx.delSub("nginx", "nginx:access");
            }
        }
    };
}
