{% set config = merged_configs.get('aws_ecr_repository', {}) %}
{% set comments = compliance_comments.get('aws_ecr_repository', []) %}
# ------------------------------------------------------------------------------
# ECR Repository
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_ecr_repository" "this" {
  name                 = "{{ config.get('name', project_id ~ '-repo') }}"
  image_tag_mutability = "{{ config.get('image_tag_mutability', 'IMMUTABLE') }}"

  image_scanning_configuration {
    scan_on_push = {{ config.get('scan_on_push', true) | lower }}
  }

  encryption_configuration {
    encryption_type = "{{ config.get('encryption_type', 'KMS') }}"
    kms_key         = {{ config.get('kms_key', 'null') }}
  }

  force_delete = {{ config.get('force_delete', false) | lower }}

  tags = {
    Name      = "{{ config.get('name', project_id ~ '-repo') }}"
    ManagedBy = "complyform"
  }
}

resource "aws_ecr_lifecycle_policy" "this" {
  repository = aws_ecr_repository.this.name

  policy = jsonencode({
    rules = [
      {
        rulePriority = 1
        description  = "Keep last {{ config.get('max_image_count', 30) }} images"
        selection = {
          tagStatus   = "any"
          countType   = "imageCountMoreThan"
          countNumber = {{ config.get('max_image_count', 30) }}
        }
        action = {
          type = "expire"
        }
      }
    ]
  })
}
