locals {
  repositories = ["helix-server", "helix-web", "helix-worker"]
}

resource "aws_ecr_repository" "this" {
  for_each = toset(local.repositories)

  # These repositories existed before Terraform state was lost and release
  # workflows publish to their stable unprefixed names.
  name                 = each.key
  image_tag_mutability = "MUTABLE"

  image_scanning_configuration {
    scan_on_push = true
  }

  tags = {
    Project     = var.project
    Environment = var.environment
  }
}

resource "aws_ecr_lifecycle_policy" "this" {
  # Keep disabled during state adoption: no policy exists live and introducing
  # one would immediately make image deletion behavior a first-adoption change.
  for_each = var.enable_lifecycle_policy ? aws_ecr_repository.this : {}

  repository = each.value.name

  policy = jsonencode({
    rules = [
      {
        rulePriority = 1
        description  = "Keep last 20 images"
        selection = {
          tagStatus   = "any"
          countType   = "imageCountMoreThan"
          countNumber = 20
        }
        action = {
          type = "expire"
        }
      }
    ]
  })
}
