# Container registries, one per service.
#
# Two repositories rather than one with tag prefixes, because the task roles that pull from them
# are separate and a single repository would make "the POC can pull the official image" the default
# rather than a decision.
#
# Created HERE and not by hand in the admin window. An earlier draft of the runbook created them
# first, on the reasoning that the CI deploy role pushes to them and cannot create them. That is
# true and it does not matter: the admin window runs `terraform apply` before CI ever runs, so the
# repositories exist by then either way, and hand-creating them first only turns the first apply
# into an import.

locals {
  ecr_repos = {
    official = "mcp-official"
    poc      = "mcp-poc"
  }
}

resource "aws_ecr_repository" "this" {
  for_each = local.ecr_repos

  name = each.value

  # A deployed digest can then never be replaced under the same tag. Without this, "roll back to the
  # previous tag" can quietly deploy something other than what was tested, which is the failure that
  # makes a rollback worse than the incident.
  image_tag_mutability = "IMMUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }

  tags = { Name = each.value }
}

# Keep the last 20 images and expire the rest.
#
# Untagged images are expired quickly: they are the layers left behind by a replaced push, they are
# not deployable, and they are billed.
resource "aws_ecr_lifecycle_policy" "this" {
  for_each = aws_ecr_repository.this

  repository = each.value.name

  policy = jsonencode({
    rules = [
      {
        rulePriority = 1
        description  = "Expire untagged images after 1 day"
        selection = {
          tagStatus   = "untagged"
          countType   = "sinceImagePushed"
          countUnit   = "days"
          countNumber = 1
        }
        action = { type = "expire" }
      },
      {
        rulePriority = 2
        description  = "Keep the 20 most recent tagged images"
        selection = {
          tagStatus   = "any"
          countType   = "imageCountMoreThan"
          countNumber = 20
        }
        action = { type = "expire" }
      },
    ]
  })
}
