resource "aws_cloudwatch_event_rule" "rule" {
  name        = var.name
  description = "Alert when ECS task stops with non-zero exit code"

  event_pattern = jsonencode({
    source        = ["aws.ecs"]
    "detail-type" = ["ECS Task State Change"]
    detail = {
      lastStatus = ["STOPPED"]
      containers = {
        exitCode = [
          {
            "anything-but" = 0
          }
        ]
      }
    }
  })
}

resource "aws_cloudwatch_event_target" "prod_ecs_failure_sns" {
  rule      = aws_cloudwatch_event_rule.rule.name
  target_id = "1"
  arn       = var.sns_topic_arn
}

resource "aws_sns_topic_policy" "allow_eventbridge" {
  arn = var.sns_topic_arn

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Principal = {
          Service = "events.amazonaws.com"
        }
        Action   = "sns:Publish"
        Resource = var.sns_topic_arn
        Condition = {
          ArnEquals = {
            "aws:SourceArn" = aws_cloudwatch_event_rule.rule.arn
          }
        }
      }
    ]
  })
}

resource "aws_cloudwatch_event_rule" "config_cf_events" {
  name = "aws-conformance-pack-cloudformation-events"

  event_pattern = jsonencode({
    source = [
      "aws.cloudformation"
    ]
  })
}

resource "aws_cloudwatch_event_target" "sns" {
  rule      = aws_cloudwatch_event_rule.config_cf_events.name
  target_id = "1"
  arn       = var.sns_topic_arn
}
