{% for dist in resources -%}
{%- set config = dist.DistributionConfigFormatted -%}
resource "aws_cloudfront_distribution" "distribution_{{ dist.name_sanitized }}" {
  comment = "{{ config.get('Comment', '') }}"
  
  {%- if config.get('aliases_formatted') %}
  aliases = [
    {%- for alias in config.aliases_formatted -%}
    "{{ alias }}",
    {%- endfor %}
  ]
  {%- endif %}

  default_root_object = "{{ config.get('DefaultRootObject', '') }}"
  enabled             = {{ config.get('Enabled', true) | lower }}
  is_ipv6_enabled     = {{ config.get('IsIPV6Enabled', true) | lower }}
  price_class         = "{{ config.get('PriceClass', 'PriceClass_All') }}"
  
  {%- if config.get('web_acl_id') %}
  web_acl_id = "{{ config.web_acl_id }}"
  {%- endif %}

  {%- for origin in config.get('origins_formatted', []) %}
  origin {
    domain_name = "{{ origin.domain_name }}"
    origin_id   = "{{ origin.origin_id }}"
    
    {%- if origin.get('origin_path') %}
    origin_path = "{{ origin.origin_path }}"
    {%- endif %}

    connection_attempts = {{ origin.get('connection_attempts', 3) }}
    connection_timeout  = {{ origin.get('connection_timeout', 10) }}

    {%- if origin.get('origin_access_control_id') %}
    origin_access_control_id = "{{ origin.origin_access_control_id }}"
    {%- endif %}

    {%- if origin.get('s3_origin_config') %}
    s3_origin_config {
      origin_access_identity = "{{ origin.s3_origin_config.get('OriginAccessIdentity', '') }}"
    }
    {%- endif %}

    {%- if origin.get('custom_origin_config') %}
    custom_origin_config {
      http_port                = {{ origin.custom_origin_config.get('HTTPPort', 80) }}
      https_port               = {{ origin.custom_origin_config.get('HTTPSPort', 443) }}
      origin_protocol_policy   = "{{ origin.custom_origin_config.get('OriginProtocolPolicy', 'https-only') }}"
      origin_ssl_protocols     = [
        {%- for protocol in origin.custom_origin_config.get('OriginSslProtocols', {}).get('Items', ['TLSv1.2']) -%}
        "{{ protocol }}",
        {%- endfor %}
      ]
      origin_read_timeout      = {{ origin.custom_origin_config.get('OriginReadTimeout', 30) }}
      origin_keepalive_timeout = {{ origin.custom_origin_config.get('OriginKeepaliveTimeout', 5) }}
    }
    {%- endif %}

    {%- if origin.get('origin_shield') and origin.origin_shield.get('Enabled') %}
    origin_shield {
      enabled              = true
      origin_shield_region = "{{ origin.origin_shield.OriginShieldRegion }}"
    }
    {%- endif %}
  }
  {%- endfor %}

  {%- for group in config.get('origin_groups_formatted', []) %}
  origin_group {
    origin_id = "{{ group.origin_id }}"

    failover_criteria {
      status_codes = [
        {%- for code in group.get('failover_criteria', {}).get('StatusCodes', {}).get('Items', []) -%}
        {{ code }},
        {%- endfor %}
      ]
    }

    {%- for member in group.get('members', []) %}
    member {
      origin_id = "{{ member.OriginId }}"
    }
    {%- endfor %}
  }
  {%- endfor %}

  {%- set default_behavior = config.get('default_cache_behavior_formatted', {}) %}
  default_cache_behavior {
    target_origin_id       = "{{ default_behavior.get('target_origin_id') }}"
    viewer_protocol_policy = "{{ default_behavior.get('viewer_protocol_policy', 'redirect-to-https') }}"
    
    allowed_methods = [
      {%- for method in default_behavior.get('allowed_methods', ['GET', 'HEAD']) -%}
      "{{ method }}",
      {%- endfor %}
    ]
    cached_methods = [
      {%- for method in default_behavior.get('cached_methods', ['GET', 'HEAD']) -%}
      "{{ method }}",
      {%- endfor %}
    ]

    compress = {{ default_behavior.get('compress', false) | lower }}

    {%- if default_behavior.get('cache_policy_id') %}
    cache_policy_id = "{{ default_behavior.cache_policy_id }}"
    {%- endif %}

    {%- if default_behavior.get('origin_request_policy_id') %}
    origin_request_policy_id = "{{ default_behavior.origin_request_policy_id }}"
    {%- endif %}

    {%- if default_behavior.get('response_headers_policy_id') %}
    response_headers_policy_id = "{{ default_behavior.response_headers_policy_id }}"
    {%- endif %}

    {%- if default_behavior.get('realtime_log_config_arn') %}
    realtime_log_config_arn = "{{ default_behavior.realtime_log_config_arn }}"
    {%- endif %}

    {%- if default_behavior.get('field_level_encryption_id') %}
    field_level_encryption_id = "{{ default_behavior.field_level_encryption_id }}"
    {%- endif %}

    {%- if not default_behavior.get('cache_policy_id') and default_behavior.get('forwarded_values') %}
    # Legacy cache behavior configuration (when not using cache policies)
    min_ttl     = {{ default_behavior.get('min_ttl', 0) }}
    default_ttl = {{ default_behavior.get('default_ttl', 86400) }}
    max_ttl     = {{ default_behavior.get('max_ttl', 31536000) }}

    forwarded_values {
      query_string = {{ default_behavior.forwarded_values.get('QueryString', false) | lower }}
      
      {%- if default_behavior.forwarded_values.get('Headers') and default_behavior.forwarded_values.Headers.get('Items') %}
      headers = [
        {%- for header in default_behavior.forwarded_values.Headers.Items -%}
        "{{ header }}",
        {%- endfor %}
      ]
      {%- endif %}

      cookies {
        forward = "{{ default_behavior.forwarded_values.get('Cookies', {}).get('Forward', 'none') }}"
        {%- if default_behavior.forwarded_values.get('Cookies', {}).get('WhitelistedNames', {}).get('Items') %}
        whitelisted_names = [
          {%- for cookie in default_behavior.forwarded_values.Cookies.WhitelistedNames.Items -%}
          "{{ cookie }}",
          {%- endfor %}
        ]
        {%- endif %}
      }

      {%- if default_behavior.forwarded_values.get('QueryStringCacheKeys', {}).get('Items') %}
      query_string_cache_keys = [
        {%- for key in default_behavior.forwarded_values.QueryStringCacheKeys.Items -%}
        "{{ key }}",
        {%- endfor %}
      ]
      {%- endif %}
    }
    {%- endif %}

    {%- for func_assoc in default_behavior.get('function_associations', []) %}
    function_association {
      event_type   = "{{ func_assoc.EventType }}"
      function_arn = "{{ func_assoc.FunctionARN }}"
    }
    {%- endfor %}

    {%- for lambda_assoc in default_behavior.get('lambda_function_associations', []) %}
    lambda_function_association {
      event_type   = "{{ lambda_assoc.EventType }}"
      lambda_arn   = "{{ lambda_assoc.LambdaFunctionARN }}"
      include_body = {{ lambda_assoc.get('IncludeBody', false) | lower }}
    }
    {%- endfor %}

    {%- if default_behavior.get('trusted_signers') %}
    trusted_signers = [
      {%- for signer in default_behavior.trusted_signers -%}
      "{{ signer }}",
      {%- endfor %}
    ]
    {%- endif %}

    {%- if default_behavior.get('trusted_key_groups') %}
    trusted_key_groups = [
      {%- for group in default_behavior.trusted_key_groups -%}
      "{{ group }}",
      {%- endfor %}
    ]
    {%- endif %}
  }

  {%- for behavior in config.get('cache_behaviors_formatted', []) %}
  ordered_cache_behavior {
    path_pattern           = "{{ behavior.path_pattern }}"
    target_origin_id       = "{{ behavior.target_origin_id }}"
    viewer_protocol_policy = "{{ behavior.viewer_protocol_policy }}"
    
    allowed_methods = [
      {%- for method in behavior.get('allowed_methods', ['GET', 'HEAD']) -%}
      "{{ method }}",
      {%- endfor %}
    ]
    cached_methods = [
      {%- for method in behavior.get('cached_methods', ['GET', 'HEAD']) -%}
      "{{ method }}",
      {%- endfor %}
    ]

    compress = {{ behavior.get('compress', false) | lower }}

    {%- if behavior.get('cache_policy_id') %}
    cache_policy_id = "{{ behavior.cache_policy_id }}"
    {%- endif %}

    {%- if behavior.get('origin_request_policy_id') %}
    origin_request_policy_id = "{{ behavior.origin_request_policy_id }}"
    {%- endif %}

    {%- if behavior.get('response_headers_policy_id') %}
    response_headers_policy_id = "{{ behavior.response_headers_policy_id }}"
    {%- endif %}

    {%- if not behavior.get('cache_policy_id') and behavior.get('forwarded_values') %}
    # Legacy cache behavior configuration
    min_ttl     = {{ behavior.get('min_ttl', 0) }}
    default_ttl = {{ behavior.get('default_ttl', 86400) }}
    max_ttl     = {{ behavior.get('max_ttl', 31536000) }}

    forwarded_values {
      query_string = {{ behavior.forwarded_values.get('QueryString', false) | lower }}
      
      cookies {
        forward = "{{ behavior.forwarded_values.get('Cookies', {}).get('Forward', 'none') }}"
      }
    }
    {%- endif %}

    {%- for func_assoc in behavior.get('function_associations', []) %}
    function_association {
      event_type   = "{{ func_assoc.EventType }}"
      function_arn = "{{ func_assoc.FunctionARN }}"
    }
    {%- endfor %}

    {%- for lambda_assoc in behavior.get('lambda_function_associations', []) %}
    lambda_function_association {
      event_type   = "{{ lambda_assoc.EventType }}"
      lambda_arn   = "{{ lambda_assoc.LambdaFunctionARN }}"
      include_body = {{ lambda_assoc.get('IncludeBody', false) | lower }}
    }
    {%- endfor %}
  }
  {%- endfor %}

  {%- for error_response in config.get('custom_error_responses_formatted', []) %}
  custom_error_response {
    error_code            = {{ error_response.error_code }}
    {%- if error_response.get('response_code') %}
    response_code         = {{ error_response.response_code }}
    {%- endif %}
    {%- if error_response.get('response_page_path') %}
    response_page_path    = "{{ error_response.response_page_path }}"
    {%- endif %}
    error_caching_min_ttl = {{ error_response.get('error_caching_min_ttl', 300) }}
  }
  {%- endfor %}

  {%- set logging = config.get('logging_config_formatted', {}) %}
  {%- if logging.get('enabled') %}
  logging_config {
    include_cookies = {{ logging.get('include_cookies', false) | lower }}
    bucket          = "{{ logging.get('bucket') }}"
    prefix          = "{{ logging.get('prefix', '') }}"
  }
  {%- endif %}

  {%- set geo_restriction = config.get('geo_restriction_formatted', {}) %}
  restrictions {
    geo_restriction {
      restriction_type = "{{ geo_restriction.get('restriction_type', 'none') }}"
      {%- if geo_restriction.get('locations') %}
      locations = [
        {%- for location in geo_restriction.locations -%}
        "{{ location }}",
        {%- endfor %}
      ]
      {%- endif %}
    }
  }

  {%- set viewer_cert = config.get('viewer_certificate_formatted', {}) %}
  viewer_certificate {
    {%- if viewer_cert.get('cloudfront_default_certificate') %}
    cloudfront_default_certificate = true
    {%- elif viewer_cert.get('acm_certificate_arn') %}
    acm_certificate_arn      = "{{ viewer_cert.acm_certificate_arn }}"
    ssl_support_method       = "{{ viewer_cert.get('ssl_support_method', 'sni-only') }}"
    minimum_protocol_version = "{{ viewer_cert.get('minimum_protocol_version', 'TLSv1.2_2021') }}"
    {%- elif viewer_cert.get('iam_certificate_id') %}
    iam_certificate_id       = "{{ viewer_cert.iam_certificate_id }}"
    ssl_support_method       = "{{ viewer_cert.get('ssl_support_method', 'sni-only') }}"
    minimum_protocol_version = "{{ viewer_cert.get('minimum_protocol_version', 'TLSv1.2_2021') }}"
    {%- else %}
    cloudfront_default_certificate = true
    {%- endif %}
  }

  tags = {
    {%- for key, value in config.get('tags_formatted', {}).items() -%}
    "{{ key }}" = "{{ value }}"
    {%- endfor %}
  }

  # Prevent accidental deletion of distributions
  lifecycle {
    prevent_destroy = true
  }
}

{%- if not loop.last %}

{% endif %}
{%- endfor %}