locals {

  # Определяем HTTP заголовки на основе значения disable_provenance
  grafana_headers = {
    "X-Disable-Provenance" = var.disable_provenance ? "true" : "false"
  }

  # IRM: читаем конфигурацию из irm/escalation.yaml
  # Метки вида "vault:key_name" заменяются значениями из Vault (secret_ext)
  _irm_raw  = yamldecode(file("${path.module}/irm/escalation.yaml"))
  _irm_ext  = data.vault_kv_secret_v2.secret_ext.data

  irm_escalation_chains = [
    for chain in local._irm_raw.chains : {
      name    = chain.name
      team_id = try(chain.team_id, null)
      steps = [
        for step in chain.steps : merge(step, {
          persons_to_notify = try([
            for p in step.persons_to_notify :
            startswith(p, "vault:") ? local._irm_ext[trimprefix(p, "vault:")] : p
          ], null)
          persons_to_notify_next_each_time = try([
            for p in step.persons_to_notify_next_each_time :
            startswith(p, "vault:") ? local._irm_ext[trimprefix(p, "vault:")] : p
          ], null)
        })
      ]
    }
  ]

  # Contact points configuration
  contact_points = [
    {
      name       = "default"
      type       = "slack"
      is_default = true
      settings = {
        webhook_url = data.vault_kv_secret_v2.secret_ext.data["mmwebhook_default"]
        template    = "../../modules/grafana_contact_points/template/alerts_message_mm.template"
      }
    },

    {
      name       = "infra-alerts-critical"
      type       = "slack"
      is_default = false
      settings = {
        webhook_url = data.vault_kv_secret_v2.secret_ext.data["mmwebhook_infra_alerts_critical"]
        template    = "../../modules/grafana_contact_points/template/alerts_message_mm.template"
      }
    },

    {
      name       = "infra-alerts-informational"
      type       = "slack"
      is_default = false
      settings = {
        webhook_url = data.vault_kv_secret_v2.secret_ext.data["mmwebhook_infra_alerts_info"]
        template    = "../../modules/grafana_contact_points/template/alerts_message_mm.template"
      }
    },

    {
      name       = "infra-alerts-test"
      type       = "slack"
      is_default = false
      settings = {
        webhook_url = data.vault_kv_secret_v2.secret_ext.data["mmwebhook_infra_alerts_test"]
        template    = "../../modules/grafana_contact_points/template/alerts_message_mm.template"
      }
    }
  ]
}
