{% set config = merged_configs.get('azurerm_virtual_network', {}) %}
{% set comments = compliance_comments.get('azurerm_virtual_network', []) %}
# ------------------------------------------------------------------------------
# Azure Virtual Network
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "azurerm_virtual_network" "this" {
  name                = "{{ config.get('name', project_id ~ '-vnet') }}"
  resource_group_name = var.resource_group_name
  location            = var.region

  address_space = {{ config.get('address_space', '["10.0.0.0/16"]') }}

  {% if config.get('dns_servers') %}
  dns_servers = {{ config.dns_servers }}
  {% endif %}

  {% if config.get('encryption_enforcement') %}
  encryption {
    enforcement = "{{ config.encryption_enforcement }}"
  }
  {% endif %}

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

resource "azurerm_subnet" "default" {
  name                 = "{{ config.get('subnet_name', 'default') }}"
  resource_group_name  = var.resource_group_name
  virtual_network_name = azurerm_virtual_network.this.name
  address_prefixes     = {{ config.get('subnet_address_prefixes', '["10.0.1.0/24"]') }}
}

resource "azurerm_network_security_group" "this" {
  name                = "{{ config.get('nsg_name', project_id ~ '-nsg') }}"
  resource_group_name = var.resource_group_name
  location            = var.region

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

resource "azurerm_subnet_network_security_group_association" "this" {
  subnet_id                 = azurerm_subnet.default.id
  network_security_group_id = azurerm_network_security_group.this.id
}

{% if config.get('flow_log_enabled', false) %}
resource "azurerm_network_watcher_flow_log" "this" {
  name                 = "{{ project_id }}-flowlog"
  network_watcher_name = "{{ config.get('network_watcher_name', 'NetworkWatcher') }}"
  resource_group_name  = "{{ config.get('network_watcher_rg', 'NetworkWatcherRG') }}"

  network_security_group_id = azurerm_network_security_group.this.id
  storage_account_id        = "{{ config.get('flow_log_storage_account_id', '') }}"
  enabled                   = true

  retention_policy {
    enabled = true
    days    = {{ config.get('flow_log_retention_days', 90) }}
  }
}
{% endif %}
