import * as cdk from "@aws-cdk/core";
import {
  ArnPrincipal,
  CompositePrincipal,
  ManagedPolicy,
  Role,
} from "@aws-cdk/aws-iam";
import { Vpc } from "@aws-cdk/aws-ec2";
import { DependencyECRRepositories } from "./dependency-repos";
import { ServiceECRRepositories } from "./service-repos";
import { LoadBalancerAccessLogsBucket } from "./lb-access-log-bucket";
import { EnvName } from "../../env-names";
import { SPIEBucketAndRoleSingleton } from "./spie-bucket-and-role-singleton";
import { SPIEBastion } from "./spie-bastion";

export interface DevInfraProps extends cdk.StackProps {
  readonly envName: EnvName;
  readonly vpcID: string;
}

/**
 * VPCInfraStack creates a stack for per-vpc and per-account resources.
 */
export class VPCInfraStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props: DevInfraProps) {
    super(scope, id, props);

    new Role(this, "JenkinsRole", {
      assumedBy: new CompositePrincipal(
        new ArnPrincipal("arn:aws:iam::043714768218:role/jenkins-prod-slave"),
        new ArnPrincipal("arn:aws:iam::043714768218:role/jenkins-prod-master")
      ),
      managedPolicies: [
        ManagedPolicy.fromAwsManagedPolicyName("AWSElasticBeanstalkFullAccess"),
        ManagedPolicy.fromAwsManagedPolicyName(
          "AmazonEC2ContainerRegistryPowerUser"
        ),
      ],
      roleName: "Jenkins",
    });

    new ServiceECRRepositories(this, "ServiceECRRepos", {
      envName: props.envName,
    });

    if (props.envName === EnvName.Staging) {
      new DependencyECRRepositories(this, "DependencyECRRepos");
    }

    new LoadBalancerAccessLogsBucket(this, "LBAccessLogsBucket", {
      envName: props.envName,
    });

    const spieInfra = new SPIEBucketAndRoleSingleton(this, 'SpieInfra'); 
    const vpc = Vpc.fromLookup(this, "Vpc", { vpcId: props.vpcID, });
    new SPIEBastion(this, 'SpieBastion', {
      vpc,
      hostClass: 'TWITCH-AUTOHOST',
      instancePolicy: spieInfra.instancePolicy,
    });
  }
}
