"use strict";
// HelloCoopStack
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HelloClientConstruct = void 0;
const cdk = __importStar(require("aws-cdk-lib"));
const constructs_1 = require("constructs");
const iam = __importStar(require("aws-cdk-lib/aws-iam"));
const lambda = __importStar(require("aws-cdk-lib/aws-lambda"));
const crypto = __importStar(require("crypto"));
const path = __importStar(require("path"));
const package_json_1 = require("../package.json");
const zipProtocolPath = path.join(__dirname, 'protocol.zip');
const zipAuthorizerPath = path.join(__dirname, 'authorizer.zip');
class HelloClientConstruct extends constructs_1.Construct {
    constructor(scope, id, props) {
        super(scope, id);
        const { region, account } = cdk.Stack.of(this);
        const loginSyncFunctionArn = props.loginSyncFunctionArn
            || (props.loginSyncFunctionName
                ? `arn:aws:lambda:${region}:${account}:function:${props.loginSyncFunctionName}`
                : null);
        const HELLO_COOKIE_SECRET = props.cookieSecret || crypto.randomBytes(32).toString('hex');
        const environment = {
            HELLO_CDK_CLIENT_VERSION: package_json_1.version,
            HELLO_COOKIE_SECRET,
            HELLO_CLIENT_ID: props.clientID,
        };
        if (loginSyncFunctionArn)
            environment['LOGIN_SYNC_FUNCTION_ARN'] = loginSyncFunctionArn;
        if (props.hostname)
            environment['HELLO_HOST'] = props.hostname;
        if (props.helloDomain)
            environment['HELLO_DOMAIN'] = props.helloDomain;
        if (props.route)
            environment['HELLO_API_ROUTE'] = props.route;
        if (props.providerHints)
            environment['HELLO_PROVIDER_HINTS'] = props.providerHints.join(' ');
        if (props.sameSiteStrict)
            environment['HELLO_SAME_SITE_STRICT'] = 'true';
        if (props.cookieToken)
            environment['HELLO_COOKIE_TOKEN'] = 'true';
        if (props.logDebug)
            environment['HELLO_DEBUG'] = 'true';
        if (props.scopes) {
            environment['HELLO_SCOPES'] = props.scopes.join(' ');
            const claims = new Set(props.scopes);
            if (claims.has('email'))
                claims.add('email_verified');
            claims.delete('openid');
            environment['HELLO_CLAIMS'] = Array.from(claims).join(' ');
        }
        const functionName = props.functionName || 'HelloClient';
        this.lambdaFunction = new lambda.Function(this, functionName, {
            functionName,
            runtime: lambda.Runtime.NODEJS_18_X,
            handler: 'index.handler',
            code: lambda.Code.fromAsset(zipProtocolPath),
            environment,
            timeout: props.timeout || cdk.Duration.seconds(30),
        });
        // if a loginFunctionTrigger is provided, attach a policy to the lambda function
        // Create a policy statement that grants invoke permission on the target Lambda
        if (loginSyncFunctionArn) {
            const policyStatement = new iam.PolicyStatement({
                actions: ['lambda:InvokeFunction'],
                resources: [loginSyncFunctionArn],
            });
            // Attach the policy statement to the invoking Lambda's execution role
            this.lambdaFunction.role?.attachInlinePolicy(new iam.Policy(this, 'InvokePolicy', {
                statements: [policyStatement],
            }));
        }
        this.functionUrl = this.lambdaFunction.addFunctionUrl({
            authType: lambda.FunctionUrlAuthType.NONE, // Publicly accessible
        });
        // Create the authorizer lambda
        const authorizerEnvironment = {
            HELLO_CDK_CLIENT_VERSION: package_json_1.version,
            HELLO_COOKIE_SECRET,
            HELLO_CLAIMS: environment['HELLO_CLAIMS'],
        };
        if (props.logDebug)
            authorizerEnvironment['HELLO_DEBUG'] = 'true';
        if (props.cognitoClaims)
            authorizerEnvironment['COGNITO_CLAIMS'] = props.cognitoClaims.join(' ');
        if (props.cognitoClientID)
            authorizerEnvironment['COGNITO_CLIENT_ID'] = props.cognitoClientID;
        this.authorizerLambda = new lambda.Function(this, 'Authorizer', {
            functionName: 'HelloClientAuthorizer',
            runtime: lambda.Runtime.NODEJS_18_X,
            code: lambda.Code.fromAsset(zipAuthorizerPath),
            handler: 'index.handler',
            environment: authorizerEnvironment,
        });
    }
}
exports.HelloClientConstruct = HelloClientConstruct;
