{% import 'common/macros.j2' as macros %}
{% for app in resources %}
{# Determine if Windows or Linux based on os_type or kind #}
{% set is_windows = app.os_type == 'windows' or (app.kind and 'linux' not in app.kind.lower()) %}
{% set resource_type = 'azurerm_windows_function_app' if is_windows else 'azurerm_linux_function_app' %}
resource "{{ resource_type }}" "{{ app.name_sanitized }}" {
  name                = "{{ app.name }}"
  location            = "{{ app.location }}"
  resource_group_name = "{{ app.resource_group_name }}"
  service_plan_id     = "{{ app.server_farm_id | replace('/serverfarms/', '/serverFarms/') }}"
  
  {% if app.storage_account_connection_string %}
  storage_account_name       = "{{ app.storage_account_name }}"
  {% set storage_reference = app.storage_account_name | find_resource_reference('azure_storage_account', 'primary_access_key', all_resources, 'storage_account_key') %}
  {% if storage_reference.startswith('azurerm_storage_account') %}
  storage_account_access_key = {{ storage_reference }}
  {% else %}
  storage_account_access_key = var.storage_account_key
  {% endif %}
  {% else %}
  {# Try to extract from app settings #}
  {% set storage_conn = app.app_settings_formatted.get('AzureWebJobsStorage', '') if app.app_settings_formatted else '' %}
  {% if storage_conn and 'AccountName=' in storage_conn %}
  {% set extracted_storage_name = storage_conn.split('AccountName=')[1].split(';')[0] %}
  storage_account_name = "{{ extracted_storage_name }}"
  {% set storage_reference = extracted_storage_name | find_resource_reference('azure_storage_account', 'primary_access_key', all_resources, 'storage_account_key') %}
  {% if storage_reference.startswith('azurerm_storage_account') %}
  storage_account_access_key = {{ storage_reference }}
  {% else %}
  storage_account_access_key = var.storage_account_key
  {% endif %}
  {% else %}
  {# Smart detection: look for storage account in same resource group #}
  {% if app.resource_group_name %}
  {% set rg_storage_name = app.resource_group_name.replace('-', '').replace('_', '').lower() + 'stor' %}
  {% if rg_storage_name == 'terrabackteststor' %}
  storage_account_name = "terrabackteststor"
  storage_account_access_key = azurerm_storage_account.terrabackteststor.primary_access_key
  {% else %}
  storage_account_name = var.function_app_storage_account_name
  storage_account_access_key = var.storage_account_key
  {% endif %}
  {% else %}
  storage_account_name = var.function_app_storage_account_name
  storage_account_access_key = var.storage_account_key
  {% endif %}
  {% endif %}
  {% endif %}
  
  {% if app.version %}
  functions_extension_version = "{{ app.version }}"
  {% elif app.app_settings_formatted and app.app_settings_formatted.get('FUNCTIONS_EXTENSION_VERSION') %}
  functions_extension_version = "{{ app.app_settings_formatted['FUNCTIONS_EXTENSION_VERSION'] }}"
  {% endif %}
  
  {% if app.daily_memory_time_quota %}
  daily_memory_time_quota = {{ app.daily_memory_time_quota }}
  {% endif %}
  
  {% if app.enabled is defined %}
  enabled = {{ app.enabled | lower }}
  {% endif %}
  
  {% if app.https_only is defined %}
  https_only = {{ app.https_only | lower }}
  {% endif %}
  
  {% if app.client_certificate_enabled is defined %}
  client_certificate_enabled = {{ app.client_certificate_enabled | lower }}
  {% endif %}
  
  {% if app.client_certificate_mode %}
  client_certificate_mode = "{{ app.client_certificate_mode }}"
  {% endif %}
  
  {% if app.builtin_logging_enabled is defined %}
  builtin_logging_enabled = {{ app.builtin_logging_enabled | lower }}
  {% endif %}

  {% if app.site_config %}
  site_config {
    {% if app.site_config.always_on is not none %}
    always_on = {{ app.site_config.always_on | lower }}
    {% endif %}
    
    {% if app.site_config.ftps_state %}
    ftps_state = "{{ app.site_config.ftps_state }}"
    {% endif %}
    
    {% if app.site_config.health_check_path %}
    health_check_path = "{{ app.site_config.health_check_path }}"
    {% endif %}
    
    {% if app.site_config.http2_enabled is not none %}
    http2_enabled = {{ app.site_config.http2_enabled | lower }}
    {% endif %}
    
    {% if app.site_config.minimum_tls_version %}
    minimum_tls_version = "{{ app.site_config.minimum_tls_version }}"
    {% endif %}
    
    {% if app.site_config.scm_minimum_tls_version %}
    scm_minimum_tls_version = "{{ app.site_config.scm_minimum_tls_version }}"
    {% endif %}
    
    {% if app.site_config.use_32_bit_worker is not none %}
    use_32_bit_worker = {{ app.site_config.use_32_bit_worker | lower }}
    {% endif %}
    
    {% if app.site_config.websockets_enabled is not none %}
    websockets_enabled = {{ app.site_config.websockets_enabled | lower }}
    {% endif %}
    
    {% if app.site_config.worker_count %}
    worker_count = {{ app.site_config.worker_count }}
    {% endif %}
    
    {# Application stack based on runtime #}
    {% if is_windows %}
    {# Windows Function App stacks #}
    {% if app.runtime_stack == 'dotnet' or (app.site_config.net_framework_version and app.site_config.net_framework_version != 'v4.0') %}
    application_stack {
      {% if app.site_config.use_dotnet_isolated_runtime %}
      dotnet_version = "{{ app.site_config.net_framework_version | replace('v', '') }}"
      use_dotnet_isolated_runtime = true
      {% else %}
      dotnet_version = "{{ app.site_config.net_framework_version | replace('v', '') }}"
      {% endif %}
    }
    {% elif app.runtime_stack == 'java' %}
    application_stack {
      java_version = "{{ app.site_config.java_version | default('11') }}"
    }
    {% elif app.runtime_stack == 'node' %}
    application_stack {
      node_version = "{{ app.site_config.node_default_version | default('14') | replace('~', '') }}"
    }
    {% elif app.runtime_stack == 'powershell' %}
    application_stack {
      powershell_core_version = "{{ app.site_config.power_shell_version | default('7') }}"
    }
    {% elif app.runtime_stack == 'python' and is_windows %}
    application_stack {
      python_version = "{{ app.site_config.python_version | default('3.9') }}"
    }
    {% endif %}
    {% else %}
    {# Linux Function App stacks #}
    {% if app.site_config.linux_fx_version %}
    {% set stack_parts = app.site_config.linux_fx_version.split('|') %}
    {% if stack_parts|length == 2 %}
      {% set runtime = stack_parts[0].lower() %}
      {% set version = stack_parts[1] %}
    application_stack {
      {% if runtime == 'docker' %}
      docker {
        registry_url = "{{ version.split('/')[0] if '/' in version and '.' in version.split('/')[0] else 'https://index.docker.io' }}"
        image_name = "{{ version.split('/')[-1].split(':')[0] }}"
        image_tag = "{{ version.split(':')[1] if ':' in version else 'latest' }}"
      }
      {% elif runtime == 'dotnet' %}
      dotnet_version = "{{ version }}"
      {% if app.site_config.use_dotnet_isolated_runtime %}
      use_dotnet_isolated_runtime = true
      {% endif %}
      {% elif runtime == 'node' %}
      node_version = "{{ version }}"
      {% elif runtime == 'python' %}
      python_version = "{{ version }}"
      {% elif runtime == 'java' %}
      java_version = "{{ version }}"
      {% elif runtime == 'powershell' %}
      powershell_core_version = "{{ version }}"
      {% endif %}
    }
    {% endif %}
    {% elif app.runtime_stack %}
    application_stack {
      {% if app.runtime_stack == 'python' %}
      python_version = "{{ app.site_config.python_version | default('3.9') }}"
      {% elif app.runtime_stack == 'node' %}
      node_version = "{{ app.site_config.node_default_version | default('14') | replace('~', '') }}"
      {% elif app.runtime_stack == 'dotnet' %}
      dotnet_version = "{{ app.site_config.net_framework_version | default('6.0') | replace('v', '') }}"
      {% if app.site_config.use_dotnet_isolated_runtime %}
      use_dotnet_isolated_runtime = true
      {% endif %}
      {% elif app.runtime_stack == 'java' %}
      java_version = "{{ app.site_config.java_version | default('11') }}"
      {% elif app.runtime_stack == 'powershell' %}
      powershell_core_version = "{{ app.site_config.power_shell_version | default('7') }}"
      {% endif %}
    }
    {% endif %}
    {% endif %}
    
    {% if app.site_config.cors %}
    cors {
      allowed_origins = {{ app.site_config.cors.allowed_origins | tojson }}
      {% if app.site_config.cors.support_credentials is not none %}
      support_credentials = {{ app.site_config.cors.support_credentials | lower }}
      {% endif %}
    }
    {% endif %}
    
    {% if app.site_config.ip_restriction %}
    {% for restriction in app.site_config.ip_restriction %}
    ip_restriction {
      {% if restriction.ip_address %}
      ip_address = "{{ restriction.ip_address }}"
      {% endif %}
      {% if restriction.service_tag %}
      service_tag = "{{ restriction.service_tag }}"
      {% endif %}
      {% if restriction.virtual_network_subnet_id %}
      virtual_network_subnet_id = "{{ restriction.virtual_network_subnet_id }}"
      {% endif %}
      {% if restriction.name %}
      name = "{{ restriction.name }}"
      {% endif %}
      {% if restriction.priority %}
      priority = {{ restriction.priority }}
      {% endif %}
      {% if restriction.action %}
      action = "{{ restriction.action }}"
      {% endif %}
    }
    {% endfor %}
    {% endif %}
    
    {% if app.site_config.scm_ip_restriction %}
    {% for restriction in app.site_config.scm_ip_restriction %}
    scm_ip_restriction {
      {% if restriction.ip_address %}
      ip_address = "{{ restriction.ip_address }}"
      {% endif %}
      {% if restriction.service_tag %}
      service_tag = "{{ restriction.service_tag }}"
      {% endif %}
      {% if restriction.virtual_network_subnet_id %}
      virtual_network_subnet_id = "{{ restriction.virtual_network_subnet_id }}"
      {% endif %}
      {% if restriction.name %}
      name = "{{ restriction.name }}"
      {% endif %}
      {% if restriction.priority %}
      priority = {{ restriction.priority }}
      {% endif %}
      {% if restriction.action %}
      action = "{{ restriction.action }}"
      {% endif %}
    }
    {% endfor %}
    {% endif %}
    
    {% if app.site_config.application_insights_connection_string %}
    application_insights_connection_string = "{{ app.site_config.application_insights_connection_string }}"
    {% endif %}
    {% if app.app_settings_formatted and app.app_settings_formatted.get('APPLICATIONINSIGHTS_CONNECTION_STRING') %}
    application_insights_connection_string = "{{ app.app_settings_formatted['APPLICATIONINSIGHTS_CONNECTION_STRING'] }}"
    {% endif %}
    
    {% if app.app_settings_formatted and app.app_settings_formatted.get('APPINSIGHTS_INSTRUMENTATIONKEY') %}
    application_insights_key = "{{ app.app_settings_formatted['APPINSIGHTS_INSTRUMENTATIONKEY'] }}"
    {% endif %}
  }
  {% endif %}

  {% if app.app_settings_formatted %}
  app_settings = {{ app.app_settings_formatted | tojson }}
  {% elif app.app_settings %}
  app_settings = {{ app.app_settings | tojson }}
  {% endif %}

  {% if app.connection_strings_formatted %}
  {% for conn_str in app.connection_strings_formatted %}
  connection_string {
    name  = "{{ conn_str.name }}"
    type  = "{{ conn_str.type }}"
    value = "{{ conn_str.value }}"
  }
  {% endfor %}
  {% endif %}

  {% if app.auth_settings and app.auth_settings.enabled %}
  auth_settings {
    enabled = true
    {% if app.auth_settings.default_provider %}
    default_provider = "{{ app.auth_settings.default_provider }}"
    {% endif %}
    {% if app.auth_settings.issuer %}
    issuer = "{{ app.auth_settings.issuer }}"
    {% endif %}
    {% if app.auth_settings.runtime_version %}
    runtime_version = "{{ app.auth_settings.runtime_version }}"
    {% endif %}
    {% if app.auth_settings.token_refresh_extension_hours %}
    token_refresh_extension_hours = {{ app.auth_settings.token_refresh_extension_hours }}
    {% endif %}
    {% if app.auth_settings.token_store_enabled is not none %}
    token_store_enabled = {{ app.auth_settings.token_store_enabled | lower }}
    {% endif %}
    {% if app.auth_settings.unauthenticated_client_action %}
    unauthenticated_client_action = "{{ app.auth_settings.unauthenticated_client_action }}"
    {% endif %}
    {% if app.auth_settings.allowed_external_redirect_urls %}
    allowed_external_redirect_urls = {{ app.auth_settings.allowed_external_redirect_urls | tojson }}
    {% endif %}
    
    {% if app.auth_settings.active_directory %}
    active_directory {
      client_id = "{{ app.auth_settings.active_directory.client_id }}"
      {% if app.auth_settings.active_directory.client_secret %}
      client_secret = "{{ app.auth_settings.active_directory.client_secret }}"
      {% endif %}
      {% if app.auth_settings.active_directory.allowed_audiences %}
      allowed_audiences = {{ app.auth_settings.active_directory.allowed_audiences | tojson }}
      {% endif %}
    }
    {% endif %}
  }
  {% endif %}
  
  {% if app.identity %}
  identity {
    type = "{{ app.identity.type }}"
    {% if app.identity.identity_ids %}
    identity_ids = {{ app.identity.identity_ids | tojson }}
    {% endif %}
  }
  {% endif %}
  
  {% if app.backup %}
  backup {
    name = "{{ app.backup.name }}"
    enabled = {{ app.backup.enabled | lower }}
    
    {% if app.backup.storage_account_url %}
    storage_account_url = "{{ app.backup.storage_account_url }}"
    {% endif %}
    
    {% if app.backup.schedule %}
    schedule {
      frequency_interval = {{ app.backup.schedule.frequency_interval }}
      frequency_unit = "{{ app.backup.schedule.frequency_unit }}"
      {% if app.backup.schedule.keep_at_least_one_backup is not none %}
      keep_at_least_one_backup = {{ app.backup.schedule.keep_at_least_one_backup | lower }}
      {% endif %}
      {% if app.backup.schedule.retention_period_days %}
      retention_period_days = {{ app.backup.schedule.retention_period_days }}
      {% endif %}
      {% if app.backup.schedule.start_time %}
      start_time = "{{ app.backup.schedule.start_time }}"
      {% endif %}
    }
    {% endif %}
  }
  {% endif %}

{{ macros.render_tags(app.tags) }}

  lifecycle {
    ignore_changes = [
      app_settings["WEBSITE_RUN_FROM_PACKAGE"],
      app_settings["WEBSITE_ENABLE_SYNC_UPDATE_SITE"],
      app_settings["AzureWebJobsStorage__accountName"]
    ]
  }
}

{% endfor %}
