/*! firebase-admin v8.10.0 */
"use strict";
/*!
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
var api_request_1 = require("../utils/api-request");
var messaging_errors_1 = require("./messaging-errors");
var batch_request_1 = require("./batch-request");
// FCM backend constants
var FIREBASE_MESSAGING_TIMEOUT = 10000;
var FIREBASE_MESSAGING_BATCH_URL = 'https://fcm.googleapis.com/batch';
var FIREBASE_MESSAGING_HTTP_METHOD = 'POST';
var FIREBASE_MESSAGING_HEADERS = {
    'X-Firebase-Client': 'fire-admin-node/8.10.0',
};
var LEGACY_FIREBASE_MESSAGING_HEADERS = {
    'X-Firebase-Client': 'fire-admin-node/8.10.0',
    'access_token_auth': 'true',
};
/**
 * Class that provides a mechanism to send requests to the Firebase Cloud Messaging backend.
 */
var FirebaseMessagingRequestHandler = /** @class */ (function () {
    /**
     * @param {FirebaseApp} app The app used to fetch access tokens to sign API requests.
     * @constructor
     */
    function FirebaseMessagingRequestHandler(app) {
        this.httpClient = new api_request_1.AuthorizedHttpClient(app);
        this.batchClient = new batch_request_1.BatchRequestClient(this.httpClient, FIREBASE_MESSAGING_BATCH_URL, FIREBASE_MESSAGING_HEADERS);
    }
    /**
     * Invokes the request handler with the provided request data.
     *
     * @param {string} host The host to which to send the request.
     * @param {string} path The path to which to send the request.
     * @param {object} requestData The request data.
     * @return {Promise<object>} A promise that resolves with the response.
     */
    FirebaseMessagingRequestHandler.prototype.invokeRequestHandler = function (host, path, requestData) {
        var request = {
            method: FIREBASE_MESSAGING_HTTP_METHOD,
            url: "https://" + host + path,
            data: requestData,
            headers: LEGACY_FIREBASE_MESSAGING_HEADERS,
            timeout: FIREBASE_MESSAGING_TIMEOUT,
        };
        return this.httpClient.send(request).then(function (response) {
            // Send non-JSON responses to the catch() below where they will be treated as errors.
            if (!response.isJson()) {
                throw new api_request_1.HttpError(response);
            }
            // Check for backend errors in the response.
            var errorCode = messaging_errors_1.getErrorCode(response.data);
            if (errorCode) {
                throw new api_request_1.HttpError(response);
            }
            // Return entire response.
            return response.data;
        })
            .catch(function (err) {
            if (err instanceof api_request_1.HttpError) {
                throw messaging_errors_1.createFirebaseError(err);
            }
            // Re-throw the error if it already has the proper format.
            throw err;
        });
    };
    /**
     * Sends the given array of sub requests as a single batch to FCM, and parses the result into
     * a BatchResponse object.
     *
     * @param {SubRequest[]} requests An array of sub requests to send.
     * @return {Promise<BatchResponse>} A promise that resolves when the send operation is complete.
     */
    FirebaseMessagingRequestHandler.prototype.sendBatchRequest = function (requests) {
        var _this = this;
        return this.batchClient.send(requests)
            .then(function (responses) {
            return responses.map(function (part) {
                return _this.buildSendResponse(part);
            });
        }).then(function (responses) {
            var successCount = responses.filter(function (resp) { return resp.success; }).length;
            return {
                responses: responses,
                successCount: successCount,
                failureCount: responses.length - successCount,
            };
        }).catch(function (err) {
            if (err instanceof api_request_1.HttpError) {
                throw messaging_errors_1.createFirebaseError(err);
            }
            // Re-throw the error if it already has the proper format.
            throw err;
        });
    };
    FirebaseMessagingRequestHandler.prototype.buildSendResponse = function (response) {
        var result = {
            success: response.status === 200,
        };
        if (result.success) {
            result.messageId = response.data.name;
        }
        else {
            result.error = messaging_errors_1.createFirebaseError(new api_request_1.HttpError(response));
        }
        return result;
    };
    return FirebaseMessagingRequestHandler;
}());
exports.FirebaseMessagingRequestHandler = FirebaseMessagingRequestHandler;
