import * as cdk from "@aws-cdk/core";
import { Repository } from "@aws-cdk/aws-ecr";
import { PolicyStatement, ArnPrincipal } from "@aws-cdk/aws-iam";
import { twitchCEHostAWS } from "../../account-ids";
import { EnvName } from "../../env-names";

export interface ServiceECRRepositoriesProps {
  readonly envName: EnvName;
}

interface RepoProps {
  readonly constructID: string;
  readonly repositoryName: string;
}

export class ServiceECRRepositories extends cdk.Construct {
  constructor(
    scope: cdk.Construct,
    id: string,
    props: ServiceECRRepositoriesProps
  ) {
    super(scope, id);

    const repoProps: RepoProps[] = [
      {
        constructID: "AutohostServer",
        repositoryName: "autohost-server",
      },
      {
        constructID: "AutohostWorker",
        repositoryName: "autohost-worker",
      },
    ];

    for (let r of repoProps) {
      const repo = new Repository(this, r.constructID, {
        repositoryName: r.repositoryName,
        removalPolicy: cdk.RemovalPolicy.DESTROY,
        lifecycleRules: [
          {
            maxImageCount: 1000,
          },
        ],
      });

      // Grant the Production account read access to the Staging repositories.
      if (props.envName == EnvName.Staging) {
        repo.addToResourcePolicy(
          new PolicyStatement({
            actions: [
              "ecr:GetAuthorizationToken",
              "ecr:BatchCheckLayerAvailability",
              "ecr:GetDownloadUrlForLayer",
              "ecr:GetRepositoryPolicy",
              "ecr:DescribeRepositories",
              "ecr:ListImages",
              "ecr:DescribeImages",
              "ecr:BatchGetImage",
              "ecr:GetLifecyclePolicy",
              "ecr:GetLifecyclePolicyPreview",
              "ecr:ListTagsForResource",
              "ecr:DescribeImageScanFindings",
            ],
            principals: [
              new ArnPrincipal(`arn:aws:iam::${twitchCEHostAWS}:root`),
            ],
          })
        );
      }
    }
  }
}
