locals {
  event_pattern = {
    detail-type = ["ECS Task State Change"]
    source      = ["aws.ecs"]
    detail = {
      desiredStatus = ["STOPPED"]
      lastStatus    = ["STOPPED"]
      containers    = {
        exitCode = [{ "anything-but" = 0 }, { "exists" : false }]
      }
    }
  }
}

data "aws_iam_policy_document" "this" {
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]

    resources = ["arn:aws:logs:*"]

    principals {
      identifiers = ["delivery.logs.amazonaws.com", "events.amazonaws.com"]
      type        = "Service"
    }
  }
}

resource "aws_cloudwatch_log_resource_policy" "this" {
  policy_document = data.aws_iam_policy_document.this.json
  policy_name     = "LogEventsPolicy"
}

resource "aws_cloudwatch_log_group" "this" {
  name              = "/ecs/stopped-tasks"
  retention_in_days = 90
}

resource "aws_cloudwatch_event_rule" "this" {
  name          = "ECSStoppedTasksEvent"
  description   = "Triggered when an Amazon ECS Task is stopped"
  event_pattern = jsonencode(local.event_pattern)
}

resource "aws_cloudwatch_event_target" "this" {
  arn  = aws_cloudwatch_log_group.this.arn
  rule = aws_cloudwatch_event_rule.this.name
}
