{%- if service.environment.active_deployment and service.settings.is_web %}
resource "google_compute_region_network_endpoint_group" "{{ service.instance_name }}" {
    provider              = google-beta
    name                  = "{{ service.instance_name }}"
    network_endpoint_type = "SERVERLESS"
    region                = "{{ env_collection.region }}"

    cloud_run {
        service = google_cloud_run_service.{{ service.instance_name }}.name
    }

    depends_on = [google_project_service.compute, google_cloud_run_service.{{ service.instance_name }}]
}

resource "google_compute_backend_service" "{{ service.instance_name }}" {
    name      = "{{ service.instance_name }}"

    protocol  = "HTTP"
    port_name = "http"
    timeout_sec = 30

    {% if service.settings.cdn.enabled %}
    enable_cdn  = true
    compression_mode = "AUTOMATIC"
    {% endif %}
    {% if service.is_frontend %}
    log_config {
      enable = true
      sample_rate = "1.0"
    }
    {% endif %}

    backend {
        group = google_compute_region_network_endpoint_group.{{ service.instance_name }}.id
    }

    {% if service.settings.custom_request_headers %}
    custom_request_headers = [{% for header in service.settings.custom_request_headers %}"{{ header.name }}:{{ header.value }}"{% if not loop.last %}, {% endif %}{% endfor %}]
    {% endif %}
    {% if service.settings.custom_response_headers %}
    custom_response_headers = [{% for header in service.settings.custom_response_headers %}"{{ header.name }}{{ header.value }}"{% if not loop.last %}, {% endif %}{% endfor %}]
    {% endif %}

    depends_on = [
      google_project_service.compute,
      google_compute_region_network_endpoint_group.{{ service.instance_name }}
    ]
}
{%- endif %}
