locals {
  v2_mutation_error_messages = [
    "createIdentity failed",
    "updateIdentity failed",
    "revokeAllTenantAccess failed",
    "revokeTenantAccess failed",
  ]

  # Build the OR query from the list of error messages
  v2_mutation_errors_query = join(" OR ", [
    for msg in local.v2_mutation_error_messages : "\\\"${msg}\\\""
  ])
}

resource "datadog_monitor" "graphql_user_v2_mutations_error_log_monitor" {
  name    = "${var.environment}-${var.service_name}-v2-mutations-error-log-monitor"
  type    = "log alert"
  message = <<-EOF
{{#is_alert}}
[${var.environment}] GraphQL User V2 mutations errors detected in logs.
Errors: ${join(", ", local.v2_mutation_error_messages)}
Notify: ${var.application_alert_channel}
{{/is_alert}}
EOF

  # Search for any of the error messages defined in locals
  query = "logs(\"service:${var.service_name} env:${var.environment} (${local.v2_mutation_errors_query})\").index(\"*\").rollup(\"count\").last(\"5m\") > ${var.v2_mutations_log_monitor_threshold}"

  monitor_thresholds {
    critical = var.v2_mutations_log_monitor_threshold
  }

  notify_no_data      = false
  notify_audit        = false
  renotify_interval   = 0
  timeout_h           = 0
  require_full_window = false

  tags = [
    "environment:${var.environment}",
    "service_name:${var.service_name}",
    "application_family:${var.application_family}"
  ]
}
