locals {
  origin_id = "${var.env}-api-backend"
}

variable "CDNALIAS" {
 type = "string"
}
variable "SSLALIAS" {
 type = "string"
}

output "test" {
  value = "${data.terraform_remote_state.app-tier.albDNSname}"
}
resource "aws_cloudfront_distribution" "main" {

  //  depends_on = ["aws_cloudfront_origin_access_identity.origin_access_identity"]
  origin {
    domain_name = "${data.terraform_remote_state.app-tier.albDNSname}"
    origin_id   = "${local.origin_id}"

    custom_origin_config {
      http_port = 80
      https_port = 443
      origin_protocol_policy = "https-only"
      origin_ssl_protocols = [ "TLSv1.1" ]
    }

  }

  web_acl_id = "${aws_waf_web_acl.waf_acl.id}"
  enabled             = true
  is_ipv6_enabled     = true
  comment             = "${var.serviceName}"

  logging_config {
    include_cookies = false
    bucket          = "${aws_s3_bucket.cloudfront-logs-bucket.id}.s3.amazonaws.com"
    prefix          = "${var.serviceName}"
    }

  //  logging_config {
  //    include_cookies = false
  //    bucket          = "cloudfrontlogs.s3.amazonaws.com"
  //    prefix          = "myprefix"
  //  }

  aliases = ["${var.CDNALIAS}", "${element(split("-", var.serviceName),0)}-api.${var.country}.${var.region}.${var.env}.meridio.co","${var.ALB_HOST_HEADER_MER}"]

  default_cache_behavior {
    allowed_methods  = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = "${local.origin_id}"


    forwarded_values {
      query_string = true
      headers = ["*"]
      cookies {
        forward = "all"
      }
    }



    viewer_protocol_policy = "redirect-to-https"
    min_ttl                = 0
    default_ttl            = 0
    max_ttl                = 0
  }




  price_class = "PriceClass_200"

  restrictions {

    geo_restriction {
      restriction_type = "none"
    }
  }

  tags {
    Environment = "${var.env}"
  }

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


resource "aws_s3_bucket" "cloudfront-logs-bucket" {
  bucket = "${var.env}-${var.serviceName}-cloudfront-logs"
  acl    = "private"
  versioning = {
    enabled = true

  }

  server_side_encryption_configuration {
    rule {
      apply_server_side_encryption_by_default {
        sse_algorithm     = "AES256"
      }
    }
  }

  tags {
    Name        = "${var.serviceName} Cloudfront Logs"

  }
}


