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

resource "aws_cloudtrail" "this" {
  name           = "{{ config.get('name', project_id ~ '-trail') }}"
  s3_bucket_name = "{{ config.get('s3_bucket_name', project_id ~ '-cloudtrail-logs') }}"
  s3_key_prefix  = "{{ config.get('s3_key_prefix', 'cloudtrail') }}"

  is_multi_region_trail         = {{ config.get('is_multi_region_trail', true) | lower }}
  include_global_service_events = {{ config.get('include_global_service_events', true) | lower }}
  enable_log_file_validation    = {{ config.get('enable_log_file_validation', true) | lower }}
  is_organization_trail         = {{ config.get('is_organization_trail', false) | lower }}

  # Encryption
  kms_key_id = {{ config.get('kms_key_id', 'null') }}

  # CloudWatch integration
  cloud_watch_logs_group_arn = {{ config.get('cloud_watch_logs_group_arn', 'null') }}
  cloud_watch_logs_role_arn  = {{ config.get('cloud_watch_logs_role_arn', 'null') }}

  # Data events
  {% if config.get('enable_s3_data_events', false) %}
  event_selector {
    read_write_type           = "{{ config.get('event_read_write_type', 'All') }}"
    include_management_events = {{ config.get('include_management_events', true) | lower }}

    data_resource {
      type   = "AWS::S3::Object"
      values = {{ config.get('s3_data_event_resources', '["arn:aws:s3"]') }}
    }
  }
  {% endif %}

  {% if config.get('enable_lambda_data_events', false) %}
  event_selector {
    read_write_type           = "All"
    include_management_events = true

    data_resource {
      type   = "AWS::Lambda::Function"
      values = ["arn:aws:lambda"]
    }
  }
  {% endif %}

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