module.exports = {
    friendlyName: 'Send push notification',

    inputs: {
        userIds: { type: 'ref' },
        topic: { type: 'string' },
        title: { type: 'string', required: true },
        body: { type: 'string', required: true },
        data: { type: 'ref' }
    },

    exits: {
        success: { responseType: 'ok' },
        forbidden: { responseType: 'forbidden' },
        badRequest: { responseType: 'badRequest' }
    },

    fn: async function (inputs, exits) {
        const { user } = this.req.token;
        const hasAdminRoleArray = (user && Array.isArray(user.roles) && user.roles.indexOf('admin') !== -1);
        const isAdmin = user && (user.typeUser === 'ADMIN' || user.typeUser === 'SUPERADMIN' || hasAdminRoleArray);
        if (!isAdmin) { return exits.forbidden({ message: 'Accès refusé' }); }

        if (!inputs.topic && (!Array.isArray(inputs.userIds) || inputs.userIds.length === 0)) {
            return exits.badRequest({ message: 'Spécifier userIds ou topic' });
        }

        if (inputs.topic) {
            const resp = await sails.helpers.sendFcm.with({ topic: inputs.topic, title: inputs.title, body: inputs.body, data: inputs.data });
            return exits.success(resp);
        }

        const tokens = await PushToken.find({ codeUser: { in: inputs.userIds } });
        const tokenList = tokens.map(t => t.fcmToken);
        const result = await sails.helpers.sendFcm.with({ tokens: tokenList, title: inputs.title, body: inputs.body, data: inputs.data });
        return exits.success({ ...result, users: inputs.userIds });
    }
};


