{% set config = merged_configs.get('azurerm_synapse_workspace', {}) %}
{% set comments = compliance_comments.get('azurerm_synapse_workspace', []) %}
# ------------------------------------------------------------------------------
# Azure Synapse Analytics Workspace
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

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

  storage_data_lake_gen2_filesystem_id = "{{ config.get('storage_data_lake_gen2_filesystem_id', '') }}"

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

  # Data exfiltration protection
  data_exfiltration_protection_enabled = {{ config.get('data_exfiltration_protection_enabled', true) | lower }}

  # SQL admin
  sql_administrator_login          = "{{ config.get('sql_administrator_login', 'sqladmin') }}"
  sql_administrator_login_password = var.synapse_sql_password

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

  identity {
    type = "{{ config.get('identity_type', 'SystemAssigned') }}"
  }

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

{% if config.get('firewall_rules') %}
{% for rule in config.firewall_rules %}
resource "azurerm_synapse_firewall_rule" "{{ rule.name | replace('-', '_') }}" {
  name                 = "{{ rule.name }}"
  synapse_workspace_id = azurerm_synapse_workspace.this.id
  start_ip_address     = "{{ rule.start_ip }}"
  end_ip_address       = "{{ rule.end_ip }}"
}
{% endfor %}
{% endif %}

variable "synapse_sql_password" {
  description = "Synapse SQL administrator password"
  type        = string
  sensitive   = true
}
