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

data "azurerm_client_config" "current" {}

resource "azurerm_key_vault" "this" {
  name                = "{{ config.get('name', project_id ~ '-kv') }}"
  resource_group_name = var.resource_group_name
  location            = var.region
  tenant_id           = data.azurerm_client_config.current.tenant_id

  sku_name = "{{ config.get('sku_name', 'standard') }}"

  # Soft delete & purge protection
  soft_delete_retention_days = {{ config.get('soft_delete_retention_days', 90) }}
  purge_protection_enabled   = {{ config.get('purge_protection_enabled', true) | lower }}

  # RBAC authorization (recommended over access policies)
  enable_rbac_authorization = {{ config.get('enable_rbac_authorization', true) | lower }}

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

  network_acls {
    default_action             = "{{ config.get('network_default_action', 'Deny') }}"
    bypass                     = "{{ config.get('network_bypass', 'AzureServices') }}"
    ip_rules                   = {{ config.get('network_ip_rules', '[]') }}
    virtual_network_subnet_ids = {{ config.get('network_subnet_ids', '[]') }}
  }

  {% if not config.get('enable_rbac_authorization', true) %}
  # Access policy for current deployer
  access_policy {
    tenant_id = data.azurerm_client_config.current.tenant_id
    object_id = data.azurerm_client_config.current.object_id

    key_permissions = [
      "Get", "List", "Create", "Delete", "Update",
      "Import", "Backup", "Restore", "Recover"
    ]

    secret_permissions = [
      "Get", "List", "Set", "Delete",
      "Backup", "Restore", "Recover"
    ]

    certificate_permissions = [
      "Get", "List", "Create", "Delete", "Update",
      "Import", "Backup", "Restore", "Recover"
    ]
  }
  {% endif %}

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

# Diagnostic settings for audit logging
{% if config.get('log_analytics_workspace_id') %}
resource "azurerm_monitor_diagnostic_setting" "key_vault" {
  name                       = "{{ project_id }}-kv-diag"
  target_resource_id         = azurerm_key_vault.this.id
  log_analytics_workspace_id = "{{ config.log_analytics_workspace_id }}"

  enabled_log {
    category = "AuditEvent"
  }

  enabled_log {
    category = "AzurePolicyEvaluationDetails"
  }

  metric {
    category = "AllMetrics"
  }
}
{% endif %}
