import * as cdk from 'aws-cdk-lib';

interface BuildParameters {
    readonly VPC: string;
    readonly TenantID: string;
    readonly ClientID: string;
}

interface BuildConfig {
    readonly Account: string;
    readonly Region: string;
    readonly ApplicationName: string;
    readonly ApplicationShortName: string;
    readonly Environment: string;
    readonly Version: string;
    readonly Parameters: BuildParameters;
}

const getValidStringValueOfKey = (buildConfig: any, key: string): string => {
    if (!buildConfig[key] || buildConfig[key].trim().length === 0) {
        throw new Error(key + ' does not exist or is empty in build config');
    }

    return buildConfig[key];
};

const getValidNumberValueOfKey = (buildConfig: any, key: string): number => {
    if (!buildConfig[key]) {
        throw new Error(key + ' does not exist or is empty in build config');
    }

    return buildConfig[key];
};

const getConfig = (app: cdk.App): BuildConfig => {
    const env = app.node.tryGetContext('config');
    if (!env) {
        throw new Error('Context variable missing on CDK command. Pass in as "-c config=env"');
    }

    const buildConfig: any = app.node.tryGetContext(env);

    if (!buildConfig) {
        throw new Error('Wrong Context variable passed on CDK command. Pass in as "-c config=env"');
    }

    const validBuildConfig: BuildConfig = {
        Account: getValidStringValueOfKey(buildConfig, 'Account'),
        Region: getValidStringValueOfKey(buildConfig, 'Region'),
        Version: getValidStringValueOfKey(buildConfig, 'Version'),
        ApplicationName: getValidStringValueOfKey(buildConfig, 'ApplicationName'),
        ApplicationShortName: getValidStringValueOfKey(buildConfig, 'ApplicationShortName'),
        Environment: getValidStringValueOfKey(buildConfig, 'Environment'),
        Parameters: {
            VPC: getValidStringValueOfKey(buildConfig['Parameters'], 'VPC'),
            TenantID: getValidStringValueOfKey(buildConfig['Parameters'], 'TenantID'),
            ClientID: getValidStringValueOfKey(buildConfig['Parameters'], 'ClientID')
        },
    };

    return validBuildConfig;
};

export { BuildConfig, BuildParameters, getConfig };