{% set config = merged_configs.get('aws_sfn_state_machine', {}) %}
{% set comments = compliance_comments.get('aws_sfn_state_machine', []) %}
# ------------------------------------------------------------------------------
# Step Functions State Machine
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_sfn_state_machine" "this" {
  name     = "{{ config.get('name', project_id ~ '-state-machine') }}"
  role_arn = {{ config.get('role_arn', 'aws_iam_role.sfn_exec.arn') }}
  type     = "{{ config.get('type', 'STANDARD') }}"

  definition = {{ config.get('definition', '"{}"') }}

  logging_configuration {
    log_destination        = "${aws_cloudwatch_log_group.sfn.arn}:*"
    include_execution_data = {{ config.get('include_execution_data', true) | lower }}
    level                  = "{{ config.get('logging_level', 'ALL') }}"
  }

  tracing_configuration {
    enabled = {{ config.get('tracing_enabled', true) | lower }}
  }

  {% if config.get('encryption_key_arn') %}
  encryption_configuration {
    kms_key_id                        = "{{ config.encryption_key_arn }}"
    type                              = "CUSTOMER_MANAGED_KMS_KEY"
    kms_data_key_reuse_period_seconds = {{ config.get('kms_data_key_reuse_period', 300) }}
  }
  {% endif %}

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

resource "aws_cloudwatch_log_group" "sfn" {
  name              = "/aws/states/{{ config.get('name', project_id ~ '-state-machine') }}"
  retention_in_days = {{ config.get('log_retention_days', 90) }}
  kms_key_id        = {{ config.get('log_kms_key_id', 'null') }}

  tags = {
    Name      = "{{ project_id }}-sfn-logs"
    ManagedBy = "complyform"
  }
}

resource "aws_iam_role" "sfn_exec" {
  name = "{{ config.get('name', project_id ~ '-state-machine') }}-exec"

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

  tags = {
    Name      = "{{ project_id }}-sfn-exec"
    ManagedBy = "complyform"
  }
}
