"use strict";
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.notificationRouter = void 0;
const koa_router_1 = __importDefault(require("koa-router"));
const typeorm_1 = require("typeorm");
const auth_base_1 = require("@things-factory/auth-base");
const fcm_1 = require("../controllers/fcm");
const debug = require('debug')('things-factory:notification:notification-router');
exports.notificationRouter = new koa_router_1.default({
    prefix: '/notification'
});
exports.notificationRouter.get('/config', async (context, next) => {
    const config = (0, fcm_1.getConfig)();
    context.type = 'application/json';
    context.body = config;
});
exports.notificationRouter.post('/register', async (context, next) => {
    const { user } = context.state;
    const { body } = context.request;
    context.body = await (0, fcm_1.register)(user, body);
    context.status = 200;
});
exports.notificationRouter.post('/unregister', async (context, next) => {
    const { user } = context.state;
    const { body } = context.request;
    context.body = await (0, fcm_1.unregister)(user, body);
    context.status = 200;
});
exports.notificationRouter.post('/notify', async (context, next) => {
    const { user, domain, notify } = context.state;
    const repository = (0, typeorm_1.getRepository)(auth_base_1.User);
    var _a = context.request.body, { receivers } = _a, options = __rest(_a, ["receivers"]);
    debug('post:/notify', receivers, receivers.split(','), options);
    // TODO filter only users having current domain privilege
    receivers = (await Promise.all(receivers
        .split(',')
        .map(email => email.trim())
        .map(async (email) => {
        var receiver = await repository.findOne({ email });
        return receiver && receiver.id;
    }))).filter(receiver => !!receiver);
    debug('post:/notify', receivers, user.id);
    await notify(Object.assign({ receivers: receivers.length > 0 ? receivers : [user.id] }, options));
    context.body = {
        success: true
    };
});
//# sourceMappingURL=notification-router.js.map