{% set config = merged_configs.get('aws_kms_key', {}) %}
{% set comments = compliance_comments.get('aws_kms_key', []) %}
# ------------------------------------------------------------------------------
# KMS Key
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_kms_key" "this" {
  description             = "{{ config.get('description', project_id ~ ' encryption key') }}"
  deletion_window_in_days = {{ config.get('deletion_window_in_days', 30) }}
  enable_key_rotation     = {{ config.get('enable_key_rotation', true) | lower }}
  rotation_period_in_days = {{ config.get('rotation_period_in_days', 365) }}
  is_enabled              = {{ config.get('is_enabled', true) | lower }}
  key_usage               = "{{ config.get('key_usage', 'ENCRYPT_DECRYPT') }}"
  customer_master_key_spec = "{{ config.get('customer_master_key_spec', 'SYMMETRIC_DEFAULT') }}"

  {% if config.get('policy') %}
  policy = jsonencode({{ config.policy }})
  {% else %}
  policy = jsonencode({
    Version = "2012-10-17"
    Id      = "{{ project_id }}-key-policy"
    Statement = [
      {
        Sid    = "EnableRootAccountAccess"
        Effect = "Allow"
        Principal = {
          AWS = "arn:aws:iam::${var.account_id}:root"
        }
        Action   = "kms:*"
        Resource = "*"
      },
      {
        Sid    = "AllowKeyAdministration"
        Effect = "Allow"
        Principal = {
          AWS = "arn:aws:iam::${var.account_id}:root"
        }
        Action = [
          "kms:Create*",
          "kms:Describe*",
          "kms:Enable*",
          "kms:List*",
          "kms:Put*",
          "kms:Update*",
          "kms:Revoke*",
          "kms:Disable*",
          "kms:Get*",
          "kms:Delete*",
          "kms:TagResource",
          "kms:UntagResource",
          "kms:ScheduleKeyDeletion",
          "kms:CancelKeyDeletion"
        ]
        Resource = "*"
      }
    ]
  })
  {% endif %}

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

resource "aws_kms_alias" "this" {
  name          = "alias/{{ config.get('alias', project_id ~ '-key') }}"
  target_key_id = aws_kms_key.this.key_id
}
