{% from "common/base_resource.tf.j2" import render_common_tags %}
{% for dist in resources %}
{% set config = dist.DistributionConfigFormatted %}
resource "aws_cloudfront_distribution" "{{ dist.name_sanitized }}" {
  {% if config.get('Comment') %}
  comment = "{{ config.Comment | escape_quotes }}"
  {% endif %}

  {% if config.get('aliases_formatted') and config.aliases_formatted | has_value %}
  aliases = [
    {% for alias in config.aliases_formatted %}
    "{{ alias }}"{{ "," if not loop.last }}
    {% endfor %}
  ]
  {% endif %}

  {% if config.get('DefaultRootObject') %}
  default_root_object = "{{ config.DefaultRootObject }}"
  {% endif %}
  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') and config.web_acl_id | has_value %}
  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') and origin.origin_path | has_value %}
    origin_path = "{{ origin.origin_path }}"
    {% endif %}

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

    {% if origin.get('origin_access_control_id') and origin.origin_access_control_id | has_value %}
    origin_access_control_id = "{{ origin.origin_access_control_id }}"
    {% elif origin.get('s3_origin_config') %}
    {# Include s3_origin_config block when present, even if OAI is empty #}
    s3_origin_config {
      {% if origin.s3_origin_config.get('OriginAccessIdentity') %}
      origin_access_identity = "{{ origin.s3_origin_config.OriginAccessIdentity }}"
      {% endif %}
    }
    {% endif %}

    {% if origin.get('custom_origin_config') %}
    custom_origin_config {
      http_port                = {{ origin.custom_origin_config.get('HTTPPort', 80) | safe_int }}
      https_port               = {{ origin.custom_origin_config.get('HTTPSPort', 443) | safe_int }}
      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 }}"{{ "," if not loop.last }}
        {% endfor %}
      ]
      origin_read_timeout      = {{ origin.custom_origin_config.get('OriginReadTimeout', 30) | safe_int }}
      origin_keepalive_timeout = {{ origin.custom_origin_config.get('OriginKeepaliveTimeout', 5) | safe_int }}
    }
    {% 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 %}

  {% 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 }}"{{ "," if not loop.last }}
      {% endfor %}
    ]
    cached_methods = [
        {% for method in default_behavior.get('cached_methods', ['GET', 'HEAD']) %}
      "{{ method }}"{{ "," if not loop.last }}
      {% endfor %}
    ]

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

      {% if default_behavior.get('cache_policy_id') and default_behavior.cache_policy_id | has_value %}
    cache_policy_id = "{{ default_behavior.cache_policy_id }}"
    {% endif %}

      {% if default_behavior.get('origin_request_policy_id') and default_behavior.origin_request_policy_id | has_value %}
    origin_request_policy_id = "{{ default_behavior.origin_request_policy_id }}"
    {% endif %}

      {% if default_behavior.get('response_headers_policy_id') and default_behavior.response_headers_policy_id | has_value %}
    response_headers_policy_id = "{{ default_behavior.response_headers_policy_id }}"
    {% endif %}

      {% if not default_behavior.get('cache_policy_id') and default_behavior.get('forwarded_values') %}
    min_ttl     = {{ default_behavior.get('min_ttl', 0) | safe_int }}
    default_ttl = {{ default_behavior.get('default_ttl', 86400) | safe_int }}
    max_ttl     = {{ default_behavior.get('max_ttl', 31536000) | safe_int }}
    
    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 }}"{{ "," if not loop.last }}
        {% 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 }}"{{ "," if not loop.last }}
          {% 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 }}"{{ "," if not loop.last }}
        {% endfor %}
      ]
      {% endif %}
    }
    {% 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 }}"{{ "," if not loop.last }}
      {% endfor %}
    ]
    cached_methods = [
      {% for method in behavior.get('cached_methods', ['GET', 'HEAD']) %}
      "{{ method }}"{{ "," if not loop.last }}
      {% endfor %}
    ]

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

    {% if behavior.get('cache_policy_id') and behavior.cache_policy_id | has_value %}
    cache_policy_id = "{{ behavior.cache_policy_id }}"
    {% endif %}

    {% if behavior.get('origin_request_policy_id') and behavior.origin_request_policy_id | has_value %}
    origin_request_policy_id = "{{ behavior.origin_request_policy_id }}"
    {% endif %}

    {% if behavior.get('response_headers_policy_id') and behavior.response_headers_policy_id | has_value %}
    response_headers_policy_id = "{{ behavior.response_headers_policy_id }}"
    {% endif %}

    {% if not behavior.get('cache_policy_id') and behavior.get('forwarded_values') %}
    min_ttl     = {{ behavior.get('min_ttl', 0) | safe_int }}
    default_ttl = {{ behavior.get('default_ttl', 86400) | safe_int }}
    max_ttl     = {{ behavior.get('max_ttl', 31536000) | safe_int }}

    forwarded_values {
      query_string = {{ behavior.forwarded_values.get('QueryString', false) | lower }}

      {% if behavior.forwarded_values.get('Headers') and behavior.forwarded_values.Headers.get('Items') %}
      headers = [
        {% for header in behavior.forwarded_values.Headers.Items %}
        "{{ header }}"{{ "," if not loop.last }}
        {% endfor %}
      ]
      {% endif %}

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

      {% if behavior.forwarded_values.get('QueryStringCacheKeys', {}).get('Items') %}
      query_string_cache_keys = [
        {% for key in behavior.forwarded_values.QueryStringCacheKeys.Items %}
        "{{ key }}"{{ "," if not loop.last }}
        {% endfor %}
      ]
      {% endif %}
    }
    {% endif %}
  }
  {% endfor %}

  restrictions {
    {% set gr = config.get('geo_restriction_formatted', {'restriction_type': 'none', 'locations': []}) %}
    geo_restriction {
      restriction_type = "{{ gr.restriction_type }}"
      {% if gr.locations %}
      locations = [
        {% for loc in gr.locations %}
        "{{ loc }}"{{ "," if not loop.last }}
        {% endfor %}
      ]
      {% endif %}
  }
  }

  {% if config.get('logging_config_formatted') and config.logging_config_formatted.enabled %}
  logging_config {
    include_cookies = {{ config.logging_config_formatted.include_cookies | lower }}
    bucket         = "{{ config.logging_config_formatted.bucket }}"
    prefix         = "{{ config.logging_config_formatted.prefix }}"
  }
  {% endif %}

  {% for cer in config.get('custom_error_responses_formatted', []) %}
  custom_error_response {
    error_code            = {{ cer.error_code }}
    {% if cer.get('response_page_path') and cer.response_page_path | has_value %}
    response_page_path    = "{{ cer.response_page_path }}"
    {% endif %}
    {% if cer.get('response_code') and cer.response_code | has_value %}
    response_code         = "{{ cer.response_code }}"
    {% endif %}
    error_caching_min_ttl = {{ cer.error_caching_min_ttl | safe_int }}
  }
  {% endfor %}

  {% set vc = config.get('viewer_certificate_formatted', {}) %}
  viewer_certificate {
    {% if vc.cloudfront_default_certificate %}
    cloudfront_default_certificate = true
    {% endif %}
    {% if vc.get('acm_certificate_arn') and vc.acm_certificate_arn | has_value %}
    acm_certificate_arn         = "{{ vc.acm_certificate_arn }}"
    {% endif %}
    {% if vc.get('iam_certificate_id') and vc.iam_certificate_id | has_value %}
    iam_certificate_id          = "{{ vc.iam_certificate_id }}"
    {% endif %}
    {% if vc.get('ssl_support_method') and vc.ssl_support_method | has_value %}
    ssl_support_method          = "{{ vc.ssl_support_method }}"
    {% endif %}
  {% if vc.get('minimum_protocol_version') and vc.minimum_protocol_version | has_value %}
    minimum_protocol_version    = "{{ vc.minimum_protocol_version }}"
  {% endif %}
  }

  {{ render_common_tags(config, indent=2) }}

  lifecycle {
    prevent_destroy = true
  }
}

{% endfor %}
