# load_balancer.tf configures Cloud Load Balancer resources for the Cloud Run service if
# var.enable_load_balancer == true.

# A network endpoint group for the "webapp" application.
resource "google_compute_region_network_endpoint_group" "webapp" {
  count = var.enable_load_balancer ? 1 : 0

  name                  = var.name
  project               = var.project
  network_endpoint_type = "SERVERLESS"
  region                = var.region
  cloud_run {
    service = google_cloud_run_v2_service.webapp.name
  }
}

resource "google_compute_ssl_policy" "default" {
  count = var.enable_load_balancer && var.ssl_policy == null ? 1 : 0

  name            = "${var.name}-modern"
  project         = var.project
  profile         = "MODERN"
  min_tls_version = "TLS_1_2"
}

# A load balancer for the "webapp" application. This is just a set of sane
# defaults. See the full documentation at [1] for customisation.
#
# [1] https://registry.terraform.io/modules/GoogleCloudPlatform/lb-http/google/latest/submodules/serverless_negs
module "webapp_http_load_balancer" {
  count = var.enable_load_balancer ? 1 : 0

  # The double slash is important(!)
  source  = "GoogleCloudPlatform/lb-http/google//modules/serverless_negs"
  version = "~> 9.0"

  project = var.project
  name    = var.name

  ssl                             = true
  managed_ssl_certificate_domains = [for k, v in var.dns_names : v]
  ssl_policy                      = var.ssl_policy == null ? google_compute_ssl_policy.default[0].id : var.ssl_policy
  https_redirect                  = true

  # Use custom TLS certs if var.use_ssl_certificates is true, otherwise, use the Google-managed certs.
  use_ssl_certificates = var.use_ssl_certificates
  ssl_certificates     = var.ssl_certificates

  # Whether to create an IPv6 address to the load balancer.
  enable_ipv6         = var.enable_ipv6
  create_ipv6_address = var.create_ipv6_address

  backends = {
    default = {
      description             = null
      protocol                = "HTTP"
      enable_cdn              = false
      custom_request_headers  = null
      custom_response_headers = null
      security_policy         = null
      compression_mode        = null

      log_config = {
        enable      = true
        sample_rate = 1.0
      }

      groups = [
        {
          group = google_compute_region_network_endpoint_group.webapp[0].id
        }
      ]

      # Currently Cloud IAP is not supported for Cloud Run endpoints. We still
      # need to specify that we don't want to use it though :).
      iap_config = {
        enable               = false
        oauth2_client_id     = null
        oauth2_client_secret = null
      }
    }
  }
}