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

resource "azurerm_storage_account" "this" {
  name                = "{{ config.get('name', project_id | replace('-', '') ~ 'sa') }}"
  resource_group_name = var.resource_group_name
  location            = var.region

  account_tier             = "{{ config.get('account_tier', 'Standard') }}"
  account_replication_type = "{{ config.get('account_replication_type', 'GRS') }}"
  account_kind             = "{{ config.get('account_kind', 'StorageV2') }}"

  # TLS
  min_tls_version = "{{ config.get('min_tls_version', 'TLS1_2') }}"

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

  # HTTPS only
  https_traffic_only_enabled = {{ config.get('https_traffic_only_enabled', true) | lower }}

  # Shared key access
  shared_access_key_enabled = {{ config.get('shared_access_key_enabled', false) | lower }}

  # Infrastructure encryption
  infrastructure_encryption_enabled = {{ config.get('infrastructure_encryption_enabled', true) | lower }}

  # Blob properties
  blob_properties {
    versioning_enabled       = {{ config.get('versioning_enabled', true) | lower }}
    change_feed_enabled      = {{ config.get('change_feed_enabled', true) | lower }}
    last_access_time_enabled = {{ config.get('last_access_time_enabled', true) | lower }}

    delete_retention_policy {
      days = {{ config.get('blob_delete_retention_days', 7) }}
    }

    container_delete_retention_policy {
      days = {{ config.get('container_delete_retention_days', 7) }}
    }
  }

  # Network rules
  network_rules {
    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 config.get('customer_managed_key') %}
  customer_managed_key {
    key_vault_key_id          = "{{ config.customer_managed_key.get('key_vault_key_id', '') }}"
    user_assigned_identity_id = "{{ config.customer_managed_key.get('user_assigned_identity_id', '') }}"
  }
  {% endif %}

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