import * as cdk from "aws-cdk-lib";
import * as config from "aws-cdk-lib/aws-config";
import { Construct } from "constructs";

export interface ConfigStackProps extends cdk.StackProps {
  readonly centralRegion: string;
  readonly bucketName: string;
  readonly roleName: string;
}

export class ConfigStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: ConfigStackProps) {
    super(scope, id, props);

    const { centralRegion, bucketName, roleName } = props;
    const { accountId, region } = new cdk.ScopedAws(this);

    new cdk.CfnCondition(this, "IncludeGlobalResourceTypesCondition", {
      expression: cdk.Fn.conditionEquals(region, centralRegion),
    });
    const includeGlobalResourceTypes = cdk.Fn.conditionIf("IncludeGlobalResourceTypesCondition", true, false);

    new config.CfnConfigurationRecorder(this, "ConfigurationRecorder", {
      roleArn: `arn:aws:iam::${accountId}:role/${roleName}`,
      recordingGroup: {
        allSupported: true,
        includeGlobalResourceTypes: includeGlobalResourceTypes,
      },
    });

    new config.CfnDeliveryChannel(this, "DeliveryChannel", {
      s3BucketName: bucketName,
      configSnapshotDeliveryProperties: {
        deliveryFrequency: "Six_Hours",
      },
    });

    const aggregator = new config.CfnConfigurationAggregator(this, "ConfigurationAggregator", {
      accountAggregationSources: [
        {
          accountIds: [accountId],
          allAwsRegions: true,
        },
      ],
    });
    aggregator.cfnOptions.condition = new cdk.CfnCondition(this, "EnableAggregator", {
      expression: cdk.Fn.conditionEquals(cdk.Stack.of(this).region, props.centralRegion),
    });
  }
}
