# Alert when any pingcap datapipeline Cloud Run Job execution fails (CRM or
# finance, extract or load). Reuses the project's existing primary notification
# channel (the one shared by dbaas_billing_alert, burn-rate, etc.) so failures
# reach wherever the team already watches.
resource "google_monitoring_alert_policy" "pipeline_job_failure" {
  depends_on = [google_pubsub_subscription.feishu_alerts, google_pubsub_topic_iam_member.monitoring_alert_publisher]

  project      = var.project_id
  display_name = "pingcap-datapipelines job failure"
  combiner     = "OR"

  conditions {
    display_name = "Cloud Run Job execution failed"

    condition_threshold {
      filter = join(" AND ", [
        "resource.type = \"cloud_run_job\"",
        "metric.type = \"run.googleapis.com/job/completed_execution_count\"",
        "metric.label.\"result\" = \"failed\"",
        "resource.label.\"job_name\" = starts_with(\"pingcap-\")",
      ])
      comparison      = "COMPARISON_GT"
      threshold_value = 0
      duration        = "0s"

      trigger {
        count = 1
      }

      aggregations {
        alignment_period   = "600s"
        per_series_aligner = "ALIGN_SUM"
      }
    }
  }

  notification_channels = [
    "projects/${var.project_id}/notificationChannels/3067816630126861020",
    google_monitoring_notification_channel.feishu_alerts.name,
  ]

  alert_strategy {
    auto_close = "604800s"
  }

  documentation {
    content   = "A pingcap datapipeline Cloud Run Job (CRM/finance extract or load) failed in ${var.project_id}. Check: gcloud run jobs executions list --region=${var.region}."
    mime_type = "text/markdown"
  }
}
