"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.notificationRouter = void 0;
const tslib_1 = require("tslib");
const koa_router_1 = tslib_1.__importDefault(require("koa-router"));
const typeorm_1 = require("typeorm");
const auth_base_1 = require("@things-factory/auth-base");
const shell_1 = require("@things-factory/shell");
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, shell_1.getRepository)(auth_base_1.User);
    var { receivers, ...options } = context.request.body;
    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.findOneBy({ email: (0, typeorm_1.ILike)(email) });
        return receiver && receiver.id;
    }))).filter(receiver => !!receiver);
    debug('post:/notify', receivers, user.id);
    await notify({
        receivers: receivers.length > 0 ? receivers : [user.id],
        ...options
    });
    context.body = {
        success: true
    };
});
//# sourceMappingURL=notification-router.js.map