/*! firebase-admin v8.7.0 */
"use strict";
/*!
 * Copyright 2019 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 validator = require("../utils/validator");
var error_1 = require("../utils/error");
var auth_config_1 = require("./auth-config");
/**
 * Tenant class that defines a Firebase Auth tenant.
 */
var Tenant = /** @class */ (function () {
    /**
     * The Tenant object constructor.
     *
     * @param {any} response The server side response used to initialize the Tenant object.
     * @constructor
     */
    function Tenant(response) {
        var tenantId = Tenant.getTenantIdFromResourceName(response.name);
        if (!tenantId) {
            throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INTERNAL_ERROR, 'INTERNAL ASSERT FAILED: Invalid tenant response');
        }
        this.tenantId = tenantId;
        this.displayName = response.displayName;
        try {
            this.emailSignInConfig = new auth_config_1.EmailSignInConfig(response);
        }
        catch (e) {
            // If allowPasswordSignup is undefined, it is disabled by default.
            this.emailSignInConfig = new auth_config_1.EmailSignInConfig({
                allowPasswordSignup: false,
            });
        }
    }
    /**
     * Builds the corresponding server request for a TenantOptions object.
     *
     * @param {TenantOptions} tenantOptions The properties to convert to a server request.
     * @param {boolean} createRequest Whether this is a create request.
     * @return {object} The equivalent server request.
     */
    Tenant.buildServerRequest = function (tenantOptions, createRequest) {
        Tenant.validate(tenantOptions, createRequest);
        var request = {};
        if (typeof tenantOptions.emailSignInConfig !== 'undefined') {
            request = auth_config_1.EmailSignInConfig.buildServerRequest(tenantOptions.emailSignInConfig);
        }
        if (typeof tenantOptions.displayName !== 'undefined') {
            request.displayName = tenantOptions.displayName;
        }
        return request;
    };
    /**
     * Returns the tenant ID corresponding to the resource name if available.
     *
     * @param {string} resourceName The server side resource name
     * @return {?string} The tenant ID corresponding to the resource, null otherwise.
     */
    Tenant.getTenantIdFromResourceName = function (resourceName) {
        // name is of form projects/project1/tenants/tenant1
        var matchTenantRes = resourceName.match(/\/tenants\/(.*)$/);
        if (!matchTenantRes || matchTenantRes.length < 2) {
            return null;
        }
        return matchTenantRes[1];
    };
    /**
     * Validates a tenant options object. Throws an error on failure.
     *
     * @param {any} request The tenant options object to validate.
     * @param {boolean} createRequest Whether this is a create request.
     */
    Tenant.validate = function (request, createRequest) {
        var validKeys = {
            displayName: true,
            emailSignInConfig: true,
        };
        var label = createRequest ? 'CreateTenantRequest' : 'UpdateTenantRequest';
        if (!validator.isNonNullObject(request)) {
            throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + "\" must be a valid non-null object.");
        }
        // Check for unsupported top level attributes.
        for (var key in request) {
            if (!(key in validKeys)) {
                throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + key + "\" is not a valid " + label + " parameter.");
            }
        }
        // Validate displayName type if provided.
        if (typeof request.displayName !== 'undefined' &&
            !validator.isNonEmptyString(request.displayName)) {
            throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "\"" + label + ".displayName\" must be a valid non-empty string.");
        }
        // Validate emailSignInConfig type if provided.
        if (typeof request.emailSignInConfig !== 'undefined') {
            // This will throw an error if invalid.
            auth_config_1.EmailSignInConfig.buildServerRequest(request.emailSignInConfig);
        }
    };
    /** @return {object} The plain object representation of the tenant. */
    Tenant.prototype.toJSON = function () {
        return {
            tenantId: this.tenantId,
            displayName: this.displayName,
            emailSignInConfig: this.emailSignInConfig && this.emailSignInConfig.toJSON(),
        };
    };
    return Tenant;
}());
exports.Tenant = Tenant;
