import * as ssm from "aws-cdk-lib/aws-ssm";
export const ENVIRONMENT_PLACEHOLDER = "__FETCH_FROM_SSM__";
export function bindEnvironment(c) {
    const binding = c.getFunctionBinding();
    const environment = {};
    if (binding) {
        Object.entries(binding.variables).forEach(([prop, variable]) => {
            const envName = getEnvironmentKey(c, prop);
            environment[envName] = variable.environment;
        });
    }
    return environment;
}
export function bindParameters(c) {
    const binding = c.getFunctionBinding();
    if (!binding) {
        return;
    }
    const app = c.node.root;
    Object.entries(binding.variables)
        .filter(([, variable]) => variable.parameter)
        .forEach(([prop, variable]) => {
        const resId = `Parameter_${prop}`;
        if (!c.node.tryFindChild(resId)) {
            new ssm.StringParameter(c, resId, {
                // Parameters, Secrets, and Jobs do not have a name
                parameterName: getParameterPath(c, prop),
                stringValue: variable.parameter,
            });
        }
    });
}
export function bindPermissions(c) {
    return c.getFunctionBinding()?.permissions || {};
}
export function bindType(c) {
    const binding = c.getFunctionBinding();
    if (!binding) {
        return;
    }
    return {
        clientPackage: binding.clientPackage,
        variables: Object.keys(binding.variables),
    };
}
export function getEnvironmentKey(c, prop) {
    return `SST_${c.constructor.name}_${prop}_${c.id}`;
}
export function getParameterPath(c, prop) {
    const app = c.node.root;
    const construct = c.constructor.name;
    return construct === "Secret"
        ? `/sst/${app.name}/${app.stage}/secrets/${c.id}`
        : `/sst/${app.name}/${app.stage}/${construct}/${c.id}/${prop}`;
}
export function getParameterFallbackPath(c, prop) {
    const app = c.node.root;
    const construct = c.constructor.name;
    return construct === "Secret"
        ? `/sst/${app.name}/.fallback/secrets/${c.id}`
        : `/sst/${app.name}/.fallback/${construct}/${c.id}/${prop}`;
}
