{% set config = merged_configs.get('azurerm_postgresql_flexible_server', {}) %}
{% set comments = compliance_comments.get('azurerm_postgresql_flexible_server', []) %}
# ------------------------------------------------------------------------------
# Azure PostgreSQL Flexible Server
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

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

  version = "{{ config.get('version', '16') }}"

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

  storage_mb = {{ config.get('storage_mb', 32768) }}

  # Network
  public_network_access_enabled = {{ config.get('public_network_access_enabled', false) | lower }}
  {% if config.get('delegated_subnet_id') %}
  delegated_subnet_id = "{{ config.delegated_subnet_id }}"
  {% endif %}
  {% if config.get('private_dns_zone_id') %}
  private_dns_zone_id = "{{ config.private_dns_zone_id }}"
  {% endif %}

  # Backup
  backup_retention_days        = {{ config.get('backup_retention_days', 35) }}
  geo_redundant_backup_enabled = {{ config.get('geo_redundant_backup_enabled', true) | lower }}

  # High availability
  {% if config.get('high_availability_mode') %}
  high_availability {
    mode = "{{ config.high_availability_mode }}"
  }
  {% endif %}

  # Authentication
  authentication {
    active_directory_auth_enabled = {{ config.get('active_directory_auth_enabled', true) | lower }}
    password_auth_enabled         = {{ config.get('password_auth_enabled', false) | lower }}
  }

  {% if config.get('customer_managed_key') %}
  customer_managed_key {
    key_vault_key_id                  = "{{ config.customer_managed_key.key_vault_key_id }}"
    primary_user_assigned_identity_id = "{{ config.customer_managed_key.primary_user_assigned_identity_id }}"
  }
  {% endif %}

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

variable "psql_admin_password" {
  description = "PostgreSQL administrator password"
  type        = string
  sensitive   = true
  default     = null
}
