import * as awsx from "@pulumi/awsx";
import * as aws from "@pulumi/aws";
import { ProviderResource } from "@pulumi/pulumi";

export const createEcrRepository = (provider: ProviderResource) => {
  const studioApiEcr = new awsx.ecr.Repository("studio-api", {
    name: "studio-api",
  });

  const policy = new aws.iam.Policy("ecr-write", {
    policy: {
      Version: "2012-10-17",
      Statement: [
        {
          Sid: "AllowPushPull",
          Effect: "Allow",
          Action: [
            "ecr:GetDownloadUrlForLayer",
            "ecr:BatchGetImage",
            "ecr:BatchCheckLayerAvailability",
            "ecr:PutImage",
            "ecr:InitiateLayerUpload",
            "ecr:UploadLayerPart",
            "ecr:CompleteLayerUpload",
          ],
          Resource: [studioApiEcr.repository.arn],
        },
        {
          Sid: "AllowGitHubActionPush",
          Effect: "Allow",
          Action: [
            "ecr:GetAuthorizationToken",
            "ecr:InitiateLayerUpload",
            "ecr:UploadLayerPart",
            "ecr:CompleteLayerUpload",
            "ecr:BatchCheckLayerAvailability",
            "ecr:PutImage",
          ],
          Resource: "*",
        },
      ],
    },
  });

  // Create a new IAM user for GitHub Actions
  const githubActionUser = new aws.iam.User("github-action-user", {
    name: "github-action-user",
  });

  // Attach policy to IAM user
  new aws.iam.UserPolicyAttachment("ecr-write-github-action-user-pa", {
    user: githubActionUser.name,
    policyArn: policy.arn,
  });

  // Create access key for IAM user
  const accessKey = new aws.iam.AccessKey("github-action-user-access-key", {
    user: githubActionUser.name,
  });

  // Create a AWS Secret Manager secret
  const secret = new aws.secretsmanager.Secret("github-action-user", {
    description: "Secret for Github Action User to access ECR",
  });

  // Add the secret values
  new aws.secretsmanager.SecretVersion("github-ecr-user-version", {
    secretId: secret.id,
    secretString: JSON.stringify({
      AWS_ACCESS_KEY_ID: accessKey.id,
      AWS_SECRET_ACCESS_KEY: accessKey.secret,
    }),
  });
  return studioApiEcr;
};
