resource "aws_cloudfront_distribution" "documents_assets" {
  # checkov:skip=CKV_AWS_310: Origin failover is not configured.
  # checkov:skip=CKV2_AWS_47: Ensure AWS CloudFront attached WAFv2 WebACL is configured with AMR for Log4j Vulnerability
  # checkov:skip=CKV_AWS_374: Ensure AWS CloudFront web distribution has geo restriction enabled
  enabled             = true
  is_ipv6_enabled     = false
  comment             = "Distribution for Stripo documents assets"
  price_class         = "PriceClass_All"
  http_version        = "http2"
  aliases             = ["${var.documents_domain}.${var.environment}-fansifter.theorchard.io"]
  default_root_object = "index.html"
  web_acl_id          = module.custom_cloudfront_waf.waf_blocking_arn_output

  origin {
    domain_name              = "${module.s3_bucket.s3_bucket_name_output}.s3.amazonaws.com"
    origin_id                = "S3-${module.s3_bucket.s3_bucket_name_output}"
    origin_access_control_id = aws_cloudfront_origin_access_control.documents.id
  }

  default_cache_behavior {
    viewer_protocol_policy = "https-only"
    compress               = false
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD"]

    response_headers_policy_id = data.aws_cloudfront_response_headers_policy.response_headers_policy.id

    target_origin_id = "S3-${module.s3_bucket.s3_bucket_name_output}"
    min_ttl          = 0
    default_ttl      = 86400
    max_ttl          = 31536000

    forwarded_values {
      query_string = false

      cookies {
        forward = "none"
      }
      headers = [
        "Origin",
        "Access-Control-Request-Headers",
        "Access-Control-Request-Method",
      ]
    }
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  logging_config {
    include_cookies = false
    bucket          = var.cloudfront_logs_bucket
  }

  viewer_certificate {
    acm_certificate_arn      = data.aws_acm_certificate.certificate.arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = "TLSv1.2_2021"
  }
}

resource "aws_cloudfront_distribution" "emple_ui" {
  # checkov:skip=CKV_AWS_310: Origin failover is not configured.
  # checkov:skip=CKV2_AWS_47: Ensure AWS CloudFront attached WAFv2 WebACL is configured with AMR for Log4j Vulnerability
  # checkov:skip=CKV_AWS_374: Ensure AWS CloudFront web distribution has geo restriction enabled
  enabled             = true
  is_ipv6_enabled     = false
  comment             = "Distribution for Stripo emple-ui"
  price_class         = "PriceClass_All"
  http_version        = "http2"
  aliases             = ["${var.environment}-${var.emple_ui_domain}.${var.environment}-fansifter.theorchard.io"]
  default_root_object = "index.html"
  web_acl_id          = module.custom_cloudfront_waf.waf_blocking_arn_output

  origin {
    domain_name              = module.stripo_emple_ui.fargate_load_balancer_dns_name
    origin_id                = module.stripo_emple_ui.fargate_load_balancer_dns_name

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

  origin {
    domain_name              = "${module.s3_bucket_custom_blocks.s3_bucket_name_output}.s3.amazonaws.com"
    origin_id                = "S3-${module.s3_bucket_custom_blocks.s3_bucket_name_output}"
    origin_access_control_id = aws_cloudfront_origin_access_control.custom_blocks.id
  }

  default_cache_behavior {
    viewer_protocol_policy = "https-only"
    compress               = false
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD"]

    response_headers_policy_id = data.aws_cloudfront_response_headers_policy.response_headers_policy.id
    cache_policy_id            = data.aws_cloudfront_cache_policy.cache_disabled_policy.id
    origin_request_policy_id   = data.aws_cloudfront_origin_request_policy.origin_request_policy.id

    target_origin_id = module.stripo_emple_ui.fargate_load_balancer_dns_name
  }

  ordered_cache_behavior {
    viewer_protocol_policy = "https-only"
    compress               = false
    path_pattern           = "/assets/img/*"
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD"]

    response_headers_policy_id = data.aws_cloudfront_response_headers_policy.response_headers_policy.id
    cache_policy_id            = data.aws_cloudfront_cache_policy.cache_policy.id
    origin_request_policy_id   = data.aws_cloudfront_origin_request_policy.origin_request_policy.id

    target_origin_id = module.stripo_emple_ui.fargate_load_balancer_dns_name
  }

   ordered_cache_behavior {
    viewer_protocol_policy = "https-only"
    compress               = false
    path_pattern           = "/custom-blocks/*"
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD"]

    response_headers_policy_id = data.aws_cloudfront_response_headers_policy.response_headers_policy.id
    cache_policy_id            = data.aws_cloudfront_cache_policy.cache_disabled_policy.id
    target_origin_id           = "S3-${module.s3_bucket_custom_blocks.s3_bucket_name_output}"
  }

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  logging_config {
    include_cookies = false
    bucket          = var.cloudfront_logs_bucket
  }

  viewer_certificate {
    acm_certificate_arn      = data.aws_acm_certificate.certificate.arn
    ssl_support_method       = "sni-only"
    minimum_protocol_version = "TLSv1.2_2021"
  }
}

# Create WAF for Cloudfront distribution
module "custom_cloudfront_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=1.5.0"
  environment       = var.environment
  service_name      = "${var.service_name}-cloudfront"
  aws_region        = var.aws_region
  acl_scope         = "CLOUDFRONT"
  count_waf_enabled = false
  block_waf_enabled = true
  excluded_rules = [
    "NoUserAgent_HEADER",
    "SizeRestrictions_BODY",
  ]
}

data "aws_cloudfront_response_headers_policy" "response_headers_policy" {
  name = "Managed-SimpleCORS"
}

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

data "aws_cloudfront_cache_policy" "cache_policy" {
  id = "83da9c7e-98b4-4e11-a168-04f0df8e2c65"
}

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

resource "aws_cloudfront_origin_access_identity" "documents_bucket_origin_access_identity" {
  comment = "access-identity-${module.s3_bucket.s3_bucket_name_output}.s3.amazonaws.com"
}

resource "aws_cloudfront_origin_access_control" "documents" {
  name                              = "${var.environment}-${var.service_name}"
  description                       = "${var.environment}-${var.service_name} Policy"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}

resource "aws_cloudfront_origin_access_control" "custom_blocks" {
  name                              = "${var.environment}-${var.service_name}-custom-blocks"
  description                       = "${var.environment}-${var.service_name} Custom Blocks Policy"
  origin_access_control_origin_type = "s3"
  signing_behavior                  = "always"
  signing_protocol                  = "sigv4"
}

resource "aws_route53_record" "route53_record" {
  name    = var.documents_domain
  zone_id = data.aws_route53_zone.route53_zone.zone_id
  type    = "CNAME"
  ttl     = "60"
  records = [aws_cloudfront_distribution.documents_assets.domain_name]
}

resource "aws_route53_record" "emple_ui_route53_record" {
  name    = "${var.environment}-${var.emple_ui_domain}"
  zone_id = data.aws_route53_zone.route53_zone.zone_id
  type    = "CNAME"
  ttl     = "60"
  records = [aws_cloudfront_distribution.emple_ui.domain_name]
}
