resource "aws_cloudfront_distribution" "api" {
  origin {
    domain_name = var.domain_name
    origin_id = "global"

    custom_origin_config {
      http_port = 80
      https_port = 443
      origin_protocol_policy = "https-only"
      origin_ssl_protocols = [ "TLSv1.1", "TLSv1.2" ]
      origin_keepalive_timeout = 5
      origin_read_timeout = 30
    }
  }

  enabled = true
  is_ipv6_enabled = true
  comment = "${var.service_name} ${var.environment} distribution"

  logging_config {
    include_cookies = false
    bucket = ""
    prefix = "cloudfront/${var.service_name}"
  }

  aliases = [ local.service_host ]

  default_cache_behavior {
    allowed_methods = [ "HEAD", "GET", "OPTIONS" ]
    cached_methods = [ "HEAD", "GET", "OPTIONS" ]
    target_origin_id = "global"
    compress = true

    forwarded_values {
      query_string = true

      cookies {
        forward = "none"
      }
    }

    viewer_protocol_policy = "redirect-to-https"
    default_ttl = 1
    max_ttl = 5
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  viewer_certificate {
    minimum_protocol_version = "TLSv1.1_2016"
    acm_certificate_arn = data.aws_acm_certificate.primary.arn
    ssl_support_method = "sni-only"
  }
}