data "aws_cloudfront_origin_request_policy" "policy" {
  name = "Managed-AllViewer"
}

data "aws_cloudfront_cache_policy" "spa_policy" {
  name = "Managed-CachingOptimized"
}

data "aws_cloudfront_cache_policy" "dynamic_policy" {
  name = "Managed-CachingDisabled"
}

data "aws_acm_certificate" "certificate" {
  domain   = "*.${var.domain_name}"
  statuses = ["ISSUED"]
}

data "aws_s3_bucket" "bucket_primary" {
  bucket = "${var.environment}-orcd-cdn"
}

data "aws_s3_bucket" "bucket_failover" {
  bucket   = "${var.environment}-orcd-cdn-us-west01"
  provider = aws.aws_us_west_2
}

# Requires corresponding change to S3 bucket policies in orcd-cdn parent folder
resource "aws_cloudfront_origin_access_identity" "origin_access_identity_primary" {
  comment = "${var.environment}-orcd-${var.service_name}-primary-origin-access-identity"
}

resource "aws_cloudfront_origin_access_identity" "origin_access_identity_failover" {
  comment = "${var.environment}-orcd-${var.service_name}-failover-origin-access-identity"
}

resource "aws_cloudfront_function" "viewer_request" {
  name    = "${var.environment}-orcd-${var.service_name}-viewer-request"
  runtime = "cloudfront-js-1.0"
  comment = "${var.environment}-orcd-${var.service_name}-viewer-request"
  publish = true
  code    = file("functions/viewer-request.js")
}

resource "aws_cloudfront_response_headers_policy" "response_headers_policy" {
  name    = "${var.environment}-orcd-${var.service_name}"
  comment = "${var.environment}-orcd-${var.service_name}"

  security_headers_config {
    content_type_options {
      override = true
    }

    frame_options {
      frame_option = "DENY"
      override     = true
    }

    referrer_policy {
      referrer_policy = "strict-origin-when-cross-origin"
      override        = true
    }

    strict_transport_security {
      access_control_max_age_sec = 365 * 24 * 60 * 60
      override                   = true
    }

    xss_protection {
      protection = true
      mode_block = true
      override   = true
    }
  }
}

resource "aws_cloudfront_distribution" "distribution" {
  # checkov:skip=CKV2_AWS_32:Cloudfront Distribution strict security headers policy. Still WIP org-wide
  # checkov:skip=ORCD_AWS_3:Ensure CloudFront distribution has a response headers policy attached. Testing below
  # checkov:skip=CKV2_AWS_47:Rule requires the AWSManagedRulesAnonymousIpList to be enabled on the WAF, which blocks legitimate traffic.
  # checkov:skip=CKV_AWS_374:Ensure AWS CloudFront web distribution has geo restriction enabled
  aliases             = ["${var.service_name}.${var.domain_name}"]
  comment             = "${var.environment}-orcd-${var.service_name}"
  enabled             = true
  is_ipv6_enabled     = true
  http_version        = "http2"
  price_class         = "PriceClass_All"
  web_acl_id          = module.custom_cloudfront_waf.waf_blocking_arn_output
  default_root_object = "index.html"

  custom_error_response {
    error_caching_min_ttl = 0
    error_code            = 404
  }

  origin_group {
    origin_id = "s3_origin_group"

    failover_criteria {
      status_codes = [403, 500, 502, 503]
    }

    member {
      origin_id = "${var.environment}-orcd-cdn"
    }

    member {
      origin_id = "${var.environment}-orcd-cdn-us-west01"
    }
  }

  origin {
    domain_name = data.aws_s3_bucket.bucket_primary.bucket_domain_name
    origin_id   = "${var.environment}-orcd-cdn"
    origin_path = "/frontend-${var.service_name}"

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.origin_access_identity_primary.cloudfront_access_identity_path
    }
  }

  origin {
    domain_name = data.aws_s3_bucket.bucket_failover.bucket_domain_name
    origin_id   = "${var.environment}-orcd-cdn-us-west01"
    origin_path = "/frontend-${var.service_name}"

    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.origin_access_identity_failover.cloudfront_access_identity_path
    }
  }

  origin {
    domain_name = "workstation-lb.${var.domain_name}" # TODO: change to cloudflare_record.workstation_lb_cname_record.name
    origin_id   = "php_origin"

    custom_origin_config {
      http_port                = 4443 # dummy, https only
      https_port               = 443
      origin_protocol_policy   = "https-only"
      origin_ssl_protocols     = ["TLSv1.2"]
      origin_keepalive_timeout = 60
      origin_read_timeout      = 60
    }
  }

  origin {
    domain_name = "ows-grass.${data.aws_route53_zone.theorchard_io_zone.name}"
    origin_id   = "grass_origin"

    custom_origin_config {
      http_port                = 4443 # dummy, https only
      https_port               = 443
      origin_protocol_policy   = "https-only"
      origin_ssl_protocols     = ["TLSv1.2"]
      origin_keepalive_timeout = 60
      origin_read_timeout      = 60
    }
  }

  # Ordered cache behaviors for all patterns
  # By specifying a cache policy, we do not explicitly specify TTLs
  # SPA path patterns should use a CachingOptimized cache policy and not use origin request policies
  # Dynamic content (i.e. custom origins in our case) should forward everything to the origin
  dynamic "ordered_cache_behavior" {
    for_each = var.ordered_cache_behaviors

    content {
      path_pattern             = ordered_cache_behavior.value.path_pattern
      allowed_methods          = ordered_cache_behavior.value.allowed_methods
      cached_methods           = ["GET", "HEAD", "OPTIONS"]
      target_origin_id         = ordered_cache_behavior.value.target_origin_id
      cache_policy_id          = ordered_cache_behavior.value.target_origin_id == "s3_origin_group" ? data.aws_cloudfront_cache_policy.spa_policy.id : data.aws_cloudfront_cache_policy.dynamic_policy.id
      origin_request_policy_id = ordered_cache_behavior.value.target_origin_id == "s3_origin_group" ? null : data.aws_cloudfront_origin_request_policy.policy.id
      compress                 = true
      viewer_protocol_policy   = "redirect-to-https"

      dynamic "function_association" {
        for_each = ordered_cache_behavior.value.viewer_request_function_enabled ? [1] : []
        content {
          event_type   = "viewer-request"
          function_arn = aws_cloudfront_function.viewer_request.arn
        }
      }
    }
  }

  # All other unmatched requests will reach the SPA
  # By specifying a cache policy, we do not explicitly specify TTLs
  default_cache_behavior {
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD", "OPTIONS"]
    target_origin_id       = "s3_origin_group"
    cache_policy_id        = data.aws_cloudfront_cache_policy.spa_policy.id
    compress               = true
    viewer_protocol_policy = "redirect-to-https"

    function_association {
      event_type   = "viewer-request"
      function_arn = aws_cloudfront_function.viewer_request.arn
    }
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  viewer_certificate {
    acm_certificate_arn      = data.aws_acm_certificate.certificate.arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = var.cloudfront_minimum_protocol_version
  }

  logging_config {
    include_cookies = true
    bucket          = var.cloudfront_logging_bucket
    prefix          = "${var.environment}-orcd-${var.service_name}"
  }

  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}
