"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.notificationMiddleware = notificationMiddleware;
const shell_1 = require("@things-factory/shell");
const env_1 = require("@things-factory/env");
const fcm_1 = require("../controllers/fcm");
const debug = require('debug')('things-factory:notification:notification-middleware');
function notifier(context) {
    return async function ({ receivers, privileges, tokens, topic, type, subject = 'info', title, body, image, url, actions, timestamp = Date.now(), mode = 'background' }) {
        const { domain, user } = context.state;
        try {
            if (mode === 'background') {
                /* for send webpush notification message */
                await (0, fcm_1.notify)({
                    receivers,
                    privileges,
                    tokens,
                    topic,
                    title,
                    body,
                    data: {
                        type,
                        url,
                        timestamp: String(timestamp)
                    },
                    image,
                    actions
                });
            }
            else {
                /* for send publish notification to clients */
                // TODO CONFIRM data format
                await shell_1.pubsub.publish('notification', {
                    notification: {
                        domain,
                        subject,
                        type,
                        title,
                        body,
                        image,
                        url,
                        timestamp
                    }
                });
            }
        }
        catch (err) {
            env_1.logger.error(err);
        }
    };
}
async function notificationMiddleware(context, next) {
    if (!context.state.notify) {
        context.state.notify = notifier(context);
    }
    await next();
}
//# sourceMappingURL=notification-middleware.js.map