import * as cdk from "aws-cdk-lib";
import {
  ArnPrincipal,
  Effect,
  IRole,
  ManagedPolicy,
  PolicyDocument,
  PolicyStatement,
  Role,
  ServicePrincipal,
} from "aws-cdk-lib/aws-iam";
import { Construct } from "constructs";

export class StackSetRoleStack extends cdk.Stack {
  readonly administrationRole: IRole;
  readonly executionRole: IRole;
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    this.administrationRole = new Role(this, "StackSetAdministrationRole", {
      roleName: "StackSetAdministrationRole",
      assumedBy: new ServicePrincipal("cloudformation.amazonaws.com"),
      inlinePolicies: {
        AssumeRole_StackSetExecutionRole: new PolicyDocument({
          statements: [
            new PolicyStatement({
              effect: Effect.ALLOW,
              actions: ["sts:AssumeRole"],
              resources: [`arn:*:iam::${this.account}:role/StackSetExecutionRole`],
            }),
          ],
        }),
      },
    });

    this.executionRole = new Role(this, "StackSetExecutionRole", {
      roleName: "StackSetExecutionRole",
      assumedBy: new ArnPrincipal(this.administrationRole.roleArn),
      managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName("AdministratorAccess")],
      inlinePolicies: {
        AssumeRole_AWSCloudFormationStackSetExecutionRole: new PolicyDocument({
          statements: [
            new PolicyStatement({
              effect: Effect.ALLOW,
              actions: ["sts:AssumeRole"],
              resources: ["*"],
            }),
          ],
        }),
      },
    });
  }
}
