import { Iam, Policy } from "../iam/PolicyDocument";
import { normalize } from "../cloudformation";
import { join } from "../Value";
export function grantTableAccess(role, policyName, tables) {
    const indexes = tables.flatMap(it => (it.properties.globalSecondaryIndexes ?? []).map(gsi => join(it.attributes.Arn(), '/index/', gsi.indexName)));
    Iam.from(role).add(policyName, Policy.allow("dynamodb:*", [...tables.map(table => table.attributes.Arn()), ...indexes]));
}
function camelCase(obj) {
    if (Array.isArray(obj))
        return obj.map(camelCase);
    if (obj) {
        if (typeof obj === 'object') {
            return Object.keys(obj).reduce((prev, key) => ({ ...prev, [key.substring(0, 1).toLowerCase() + key.substring(1)]: camelCase(obj[key]) }), {});
        }
    }
    return obj;
}
export function dynamoTable(aws, props, name) {
    const table = aws.dynamodb.table({ ...camelCase(props), ...(name ? { tableName: name } : {}) });
    if (name) {
        return table.withLogicalName(normalize(name));
    }
    return table;
}
