import * as cdk from "@aws-cdk/core";
import {
  AttributeType,
  BillingMode,
  StreamViewType,
  Table,
} from "@aws-cdk/aws-dynamodb";
import { EnvName } from "../../env-names";
import { RemovalPolicy } from "@aws-cdk/core";
import { WorkerSSMParamters } from "./worker-ssm-parameters";
import { TwitchSecurityLogFunnelSubscriptions } from "./twitch-security-log-funnel-subscriptions";

export interface ServiceInfraStackProps extends cdk.StackProps {
  readonly envName: EnvName;
}

/**
 * ServiceInfraStack creates a stack for autohost and hosting service related
 * infrastructure. There may be multiple service-infra stacks per AWS account.
 */
export class ServiceInfraStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props: ServiceInfraStackProps) {
    super(scope, id, props);

    this.addDynamoDBTables(props);

    // Add SSM parameters for Autohost Worker.
    if (props.envName == EnvName.Production) {
      new WorkerSSMParamters(this, "WorkerSSMParams", {
        keyPrefix: "production",
      });
    }

    new TwitchSecurityLogFunnelSubscriptions(this, "LogFunnelSubs", {
      envName: props.envName,
    });
  }

  private addDynamoDBTables(props: ServiceInfraStackProps) {
    // Create DynamoDB table for auto-hosting settings.
    new Table(this, "SettingsTable", {
      tableName: `${props.envName}-settings`,
      billingMode: BillingMode.PAY_PER_REQUEST,
      partitionKey: {
        name: "ChannelID",
        type: AttributeType.STRING,
      },
      pointInTimeRecovery: true,
      replicationRegions: ["us-east-2"],
      removalPolicy: RemovalPolicy.DESTROY,
      stream: StreamViewType.NEW_AND_OLD_IMAGES,
    });
  }
}
