"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lambda_ref_1 = require("./lambda-ref");
const lambda_generated_1 = require("./lambda.generated");
/**
 * A new alias to a particular version of a Lambda function.
 */
class Alias extends lambda_ref_1.FunctionRef {
    constructor(parent, name, props) {
        super(parent, name);
        this.canCreatePermissions = true; // Not used anyway
        this.underlyingLambda = props.version.lambda;
        const alias = new lambda_generated_1.cloudformation.AliasResource(this, 'Resource', {
            aliasName: props.aliasName,
            description: props.description,
            functionName: this.underlyingLambda.functionName,
            functionVersion: props.version.functionVersion,
            routingConfig: this.determineRoutingConfig(props)
        });
        this.functionName = alias.ref;
        this.functionArn = alias.ref;
    }
    addPermission(name, permission) {
        // Forward addPermission() to the underlying Lambda object
        this.underlyingLambda.addPermission(name, permission);
    }
    /**
     * Calculate the routingConfig parameter from the input props
     */
    determineRoutingConfig(props) {
        if (!props.additionalVersions || props.additionalVersions.length === 0) {
            return undefined;
        }
        this.validateAdditionalWeights(props.additionalVersions);
        return {
            additionalVersionWeights: props.additionalVersions.map(vw => {
                return {
                    functionVersion: vw.version.functionVersion,
                    functionWeight: vw.weight
                };
            })
        };
    }
    /**
     * Validate that the additional version weights make sense
     *
     * We validate that they are positive and add up to something <= 1.
     */
    validateAdditionalWeights(weights) {
        const total = weights.map(w => {
            if (w.weight < 0 || w.weight > 1) {
                throw new Error(`Additional version weight must be between 0 and 1, got: ${w.weight}`);
            }
            return w.weight;
        }).reduce((a, x) => a + x);
        if (total > 1) {
            throw new Error(`Sum of additional version weights must not exceed 1, got: ${total}`);
        }
    }
}
exports.Alias = Alias;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYWxpYXMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJhbGlhcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBLDZDQUF5RDtBQUV6RCx5REFBaUU7QUE4Q2pFOztHQUVHO0FBQ0gsTUFBYSxLQUFNLF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