{% set config = merged_configs.get('aws_eks_node_group', {}) %}
{% set comments = compliance_comments.get('aws_eks_node_group', []) %}
# ------------------------------------------------------------------------------
# EKS Managed Node Group
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_eks_node_group" "this" {
  cluster_name    = aws_eks_cluster.this.name
  node_group_name = "{{ config.get('node_group_name', project_id ~ '-node-group') }}"
  node_role_arn   = {{ config.get('node_role_arn', 'aws_iam_role.eks_node.arn') }}
  subnet_ids      = {{ config.get('subnet_ids', '[]') }}

  instance_types = {{ config.get('instance_types', '["t3.medium"]') }}
  capacity_type  = "{{ config.get('capacity_type', 'ON_DEMAND') }}"
  disk_size      = {{ config.get('disk_size', 50) }}

  scaling_config {
    desired_size = {{ config.get('desired_size', 2) }}
    max_size     = {{ config.get('max_size', 4) }}
    min_size     = {{ config.get('min_size', 1) }}
  }

  update_config {
    max_unavailable = {{ config.get('max_unavailable', 1) }}
  }

  {% if config.get('labels') %}
  labels = {{ config.labels }}
  {% endif %}

  tags = {
    Name      = "{{ config.get('node_group_name', project_id ~ '-node-group') }}"
    ManagedBy = "complyform"
  }

  depends_on = [
    aws_iam_role_policy_attachment.eks_node_policy,
    aws_iam_role_policy_attachment.eks_cni_policy,
    aws_iam_role_policy_attachment.ecr_read_only,
  ]
}

resource "aws_iam_role" "eks_node" {
  name = "{{ project_id }}-eks-node-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      }
    ]
  })

  tags = {
    Name      = "{{ project_id }}-eks-node-role"
    ManagedBy = "complyform"
  }
}

resource "aws_iam_role_policy_attachment" "eks_node_policy" {
  role       = aws_iam_role.eks_node.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy"
}

resource "aws_iam_role_policy_attachment" "eks_cni_policy" {
  role       = aws_iam_role.eks_node.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy"
}

resource "aws_iam_role_policy_attachment" "ecr_read_only" {
  role       = aws_iam_role.eks_node.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
}
