import * as cdk from "aws-cdk-lib";
import { ManagedPolicy, Role, ServicePrincipal } from "aws-cdk-lib/aws-iam";
import { CfnAccountAlias, CfnSlackChannelConfiguration } from "aws-cdk-lib/aws-supportapp";
import { Construct } from "constructs";
import { SLACK_WORKSPACE_ID } from "./const";

export type SupportAppProps = {
  readonly slackChannelId: string;
  readonly slackChannelName: string;
};

interface StackProps extends cdk.StackProps {
  readonly accountAlias: string;
  readonly supportAppProps: SupportAppProps;
}

export class SupportAppStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);
    const { accountAlias } = props;
    const { slackChannelId, slackChannelName } = props.supportAppProps;

    const role = new Role(this, "AWSSupportAppRole", {
      roleName: "AWSSupportAppRole",
      assumedBy: new ServicePrincipal("supportapp.amazonaws.com"),
      managedPolicies: [ManagedPolicy.fromAwsManagedPolicyName("AWSSupportAppFullAccess")],
    });

    new CfnAccountAlias(this, "AccountAlias", {
      accountAlias,
    });

    new CfnSlackChannelConfiguration(this, "SlackChannelConfiguration", {
      teamId: SLACK_WORKSPACE_ID,
      channelName: slackChannelName,
      channelId: slackChannelId,
      channelRoleArn: role.roleArn,
      notifyOnCaseSeverity: "all",
      notifyOnAddCorrespondenceToCase: true,
      notifyOnCreateOrReopenCase: true,
      notifyOnResolveCase: true,
    });
  }
}
