"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.directiveNotification = exports.notificationDirectiveTypeDefs = void 0;
const tslib_1 = require("tslib");
const graphql_1 = require("graphql");
const graphql_tag_1 = tslib_1.__importDefault(require("graphql-tag"));
const utils_1 = require("@graphql-tools/utils");
const debug = require('debug')('things-factory:notification:directive-notification');
const DIRECTIVE = 'notification';
exports.notificationDirectiveTypeDefs = (0, graphql_tag_1.default) `
  directive @notification(
    receivers: String
    topic: String
    subject: String # info
    title: String
    body: String
    image: String
    url: String
    # timestamp = String(Date.now())
    mode: String # background
  ) on FIELD_DEFINITION
`;
const directiveNotification = (schema) => (0, utils_1.mapSchema)(schema, {
    [utils_1.MapperKind.OBJECT_FIELD]: (fieldConfig, fieldName, typeName, schema) => {
        const notificationDirective = (0, utils_1.getDirective)(schema, fieldConfig, DIRECTIVE)?.[0];
        if (notificationDirective) {
            const { resolve = graphql_1.defaultFieldResolver, args } = fieldConfig;
            if (!args) {
                throw new Error(`Unexpected Error. args should be defined in @notification directive for field ${fieldName}.`);
            }
            const { receivers, topic, subject = 'info', title, body, image, url, mode = 'background' } = notificationDirective;
            const timestamp = Date.now();
            fieldConfig.resolve = async function (source, args, context, info) {
                const result = await resolve.call(this, source, args, context, info);
                const { domain, user, notify } = context.state;
                if (!notify) {
                    debug('notify not set');
                }
                else {
                    try {
                        await notify({
                            receivers: [user.id],
                            notificationDirective,
                            timestamp: new Date()
                        });
                    }
                    catch (err) {
                        debug(err);
                    }
                }
                return result;
            };
            return fieldConfig;
        }
    }
});
exports.directiveNotification = directiveNotification;
//# sourceMappingURL=directive-notification.js.map