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

resource "aws_eks_cluster" "this" {
  name     = "{{ config.get('name', project_id ~ '-eks') }}"
  role_arn = {{ config.get('role_arn', 'aws_iam_role.eks_cluster.arn') }}
  version  = "{{ config.get('version', '1.31') }}"

  vpc_config {
    subnet_ids              = {{ config.get('subnet_ids', '[]') }}
    security_group_ids      = {{ config.get('security_group_ids', '[]') }}
    endpoint_private_access = {{ config.get('endpoint_private_access', true) | lower }}
    endpoint_public_access  = {{ config.get('endpoint_public_access', false) | lower }}
  }

  # Logging
  enabled_cluster_log_types = {{ config.get('enabled_cluster_log_types', '["api", "audit", "authenticator", "controllerManager", "scheduler"]') }}

  # Encryption
  {% if config.get('encryption_key_arn') %}
  encryption_config {
    provider {
      key_arn = "{{ config.encryption_key_arn }}"
    }
    resources = ["secrets"]
  }
  {% endif %}

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

  depends_on = [
    aws_iam_role_policy_attachment.eks_cluster_policy,
    aws_iam_role_policy_attachment.eks_service_policy,
  ]
}

resource "aws_iam_role" "eks_cluster" {
  name = "{{ config.get('name', project_id ~ '-eks') }}-cluster-role"

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

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

resource "aws_iam_role_policy_attachment" "eks_cluster_policy" {
  role       = aws_iam_role.eks_cluster.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
}

resource "aws_iam_role_policy_attachment" "eks_service_policy" {
  role       = aws_iam_role.eks_cluster.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy"
}
