import logger from '@adonisjs/core/services/logger';
import { getMessaging } from 'firebase-admin/messaging';
import _ from 'lodash';
export class AKPushNotificationService {
    tokenService;
    constructor(tokenService) {
        this.tokenService = tokenService;
    }
    async send(recipient, title, body, data, tokenType) {
        const tokens = await this.tokenService.list(recipient, tokenType);
        const rawTokens = _.map(tokens, (t) => t.token);
        if (!_.isEmpty(rawTokens)) {
            const response = await getMessaging().sendEachForMulticast({
                tokens: rawTokens,
                webpush: {
                    data,
                    notification: {
                        title,
                        body,
                    },
                },
            });
            const deleteCodes = [
                'messaging/invalid-recipient',
                'messaging/invalid-registration-token',
                'messaging/registration-token-not-registered',
            ];
            const tokensToDelete = [];
            for (const index in response.responses) {
                const error = response.responses[index].error;
                if (error) {
                    if (deleteCodes.includes(error.code))
                        tokensToDelete.push(rawTokens[index]);
                    else
                        logger.error(error.toJSON());
                }
            }
            if (!_.isEmpty(tokensToDelete)) {
                await this.tokenService.deleteTokens(tokensToDelete);
            }
        }
    }
}
//# sourceMappingURL=push_notification_service.js.map