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

resource "azurerm_mssql_database" "this" {
  name      = "{{ config.get('name', project_id ~ '-sqldb') }}"
  server_id = azurerm_mssql_server.this.id

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

  max_size_gb = {{ config.get('max_size_gb', 250) }}

  collation = "{{ config.get('collation', 'SQL_Latin1_General_CP1_CI_AS') }}"

  # Transparent Data Encryption
  transparent_data_encryption_enabled = {{ config.get('transparent_data_encryption_enabled', true) | lower }}

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

  # Geo-redundant backup
  geo_backup_enabled = {{ config.get('geo_backup_enabled', true) | lower }}

  # Zone redundancy
  zone_redundant = {{ config.get('zone_redundant', false) | lower }}

  # Ledger
  ledger_enabled = {{ config.get('ledger_enabled', false) | lower }}

  {% if config.get('short_term_retention_policy_days') %}
  short_term_retention_policy {
    retention_days           = {{ config.get('short_term_retention_policy_days', 7) }}
    backup_interval_in_hours = {{ config.get('backup_interval_in_hours', 12) }}
  }
  {% endif %}

  {% if config.get('long_term_retention_policy') %}
  long_term_retention_policy {
    weekly_retention  = "{{ config.long_term_retention_policy.get('weekly_retention', 'P1W') }}"
    monthly_retention = "{{ config.long_term_retention_policy.get('monthly_retention', 'P1M') }}"
    yearly_retention  = "{{ config.long_term_retention_policy.get('yearly_retention', 'P1Y') }}"
    week_of_year      = {{ config.long_term_retention_policy.get('week_of_year', 1) }}
  }
  {% endif %}

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