{% set config = merged_configs.get('azurerm_linux_function_app', {}) %}
{% set comments = compliance_comments.get('azurerm_linux_function_app', []) %}
# ------------------------------------------------------------------------------
# Azure Linux Function App
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "azurerm_service_plan" "functions" {
  name                = "{{ config.get('plan_name', project_id ~ '-func-plan') }}"
  resource_group_name = var.resource_group_name
  location            = var.region
  os_type             = "Linux"
  sku_name            = "{{ config.get('sku_name', 'EP1') }}"

  tags = {
    Name      = "{{ config.get('plan_name', project_id ~ '-func-plan') }}"
    ManagedBy = "complyform"
  }
}

resource "azurerm_linux_function_app" "this" {
  name                = "{{ config.get('name', project_id ~ '-func') }}"
  resource_group_name = var.resource_group_name
  location            = var.region
  service_plan_id     = azurerm_service_plan.functions.id

  storage_account_name       = "{{ config.get('storage_account_name', '') }}"
  storage_account_access_key = {{ config.get('storage_account_access_key', 'null') }}

  https_only = {{ config.get('https_only', true) | lower }}

  public_network_access_enabled = {{ config.get('public_network_access_enabled', false) | lower }}

  site_config {
    minimum_tls_version = "{{ config.get('minimum_tls_version', '1.2') }}"
    http2_enabled       = {{ config.get('http2_enabled', true) | lower }}
    ftps_state          = "{{ config.get('ftps_state', 'Disabled') }}"

    {% if config.get('application_stack') %}
    application_stack {
      {% if config.application_stack.get('python_version') %}
      python_version = "{{ config.application_stack.python_version }}"
      {% endif %}
      {% if config.application_stack.get('node_version') %}
      node_version = "{{ config.application_stack.node_version }}"
      {% endif %}
    }
    {% endif %}

    application_insights_connection_string = {{ config.get('application_insights_connection_string', 'null') }}
  }

  identity {
    type = "{{ config.get('identity_type', 'SystemAssigned') }}"
  }

  app_settings = {
    "FUNCTIONS_WORKER_RUNTIME" = "{{ config.get('worker_runtime', 'python') }}"
    {% for key, value in config.get('app_settings', {}).items() %}
    "{{ key }}" = "{{ value }}"
    {% endfor %}
  }

  tags = {
    Name      = "{{ config.get('name', project_id ~ '-func') }}"
    ManagedBy = "complyform"
  }
}
