module "cloudfront" {
  source = "../modules/cloudfront"

  providers = {
    aws = aws.aws
  }

  depends_on = [
    module.s3,
    module.apigw,
    module.acm
  ]

  enabled    = true
  web_acl_id = module.waf.web_acl_arn
  aliases = [
    local.domain,
    "www.${local.domain}"
  ]

  acm_certificate_arn = module.acm.certificate_arn
  default_root_object = "index.html"

  origin = {
    api-gateway = {
      domain_name = replace(replace(module.apigw.endpoint, "https://", ""), "/", "")
      origin_path = "/api"

      custom_origin_config = {
        http_port              = 80
        https_port             = 443
        origin_protocol_policy = "match-viewer"
        origin_ssl_protocols   = ["TLSv1", "TLSv1.1", "TLSv1.2"]
      }
    }
    s3 = {
      domain_name = module.s3["website"].domain_name

      s3_origin_config = {
        origin_access_identity = module.s3["website"].cloudfront_access_identity
      }
    }
  }

  default_cache_behavior = {
    target_origin_id       = "s3"
    viewer_protocol_policy = "redirect-to-https"

    allowed_methods = ["GET", "HEAD", "OPTIONS"]
    cached_methods  = ["GET", "HEAD"]

    min_ttl     = 0
    default_ttl = 3600
    max_ttl     = 86400

    forwarded_values = {
      query_string = false

      cookies = {
        forward = "none"
      }
    }
  }
}
