locals {
  # Default template for Telegram messages
  default_telegram_message_template = try(
    fileexists("${path.module}/template/alerts_message_tg.template") ?
    replace(file("${path.module}/template/alerts_message_tg.template"), "__ORG_ID__", var.org_id) :
    "Default message template",
    "Default message template"
  )

  # Preparing settings for each contact point
  contact_point_templates = {
    for cp in var.contact_points :
    cp.name => {
      name     = cp.name
      type     = cp.type
      settings = cp.settings
      # Check and load template from variables if specified and file exists
      template = try(
        (cp.settings["template"] != null && fileexists(cp.settings["template"])) ?
        replace(replace(replace(file(cp.settings["template"]), "__ENV__", var.env), "__ORG_ID__", var.org_id), "__GRAFANA_URL__", var.grafana_url) :
        local.default_telegram_message_template,
        local.default_telegram_message_template
      )
      # Check and load title template if specified and file exists
      title = try(
        (cp.settings["title_template"] != null && fileexists(cp.settings["title_template"])) ?
        replace(replace(replace(file(cp.settings["title_template"]), "__ENV__", var.env), "__ORG_ID__", var.org_id), "__GRAFANA_URL__", var.grafana_url) :
        null,
        null
      )
    }
  }
}
