data "aws_cloudwatch_log_group" "datadog_agent" {
  name = "/ecs/${local.name_prefix}-datadog-agent"
}

resource "aws_cloudwatch_metric_alarm" "images_api_v2_high" {
  alarm_name          = "${local.name_prefix}-api-high_usage"
  alarm_description   = "CPU usage or number of requests is higher than threshold."
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = 1
  threshold           = 1
  actions_enabled     = true
  alarm_actions       = [module.images_api_appautoscaling.scaling_up_policy.arn]

  metric_query {
    id          = "check_thresholds"
    expression  = "(cpu >= 40 OR requests_per_target >= 50)"
    label       = "CPU utilization and Requests per target limits"
    return_data = true
  }

  metric_query {
    id          = "cpu"
    return_data = false

    metric {
      metric_name = "CPUUtilization"
      namespace   = "AWS/ECS"
      period      = "60"
      stat        = "Average"

      dimensions = {
        ClusterName = data.aws_ecs_cluster.main.cluster_name
        ServiceName = aws_ecs_service.main.name
      }
    }
  }

  metric_query {
    id          = "requests_per_target"
    return_data = false

    metric {
      metric_name = "RequestCountPerTarget"
      namespace   = "AWS/ApplicationELB"
      period      = "60"
      stat        = "Sum"

      dimensions = {
        TargetGroup = aws_lb_target_group.main.arn_suffix
      }
    }
  }
}

resource "aws_cloudwatch_metric_alarm" "images_api_low" {
  alarm_name          = "${local.name_prefix}-api_low_usage"
  alarm_description   = "CPU usage and number of requests is lower than threshold."
  comparison_operator = "GreaterThanOrEqualToThreshold"
  evaluation_periods  = 3
  threshold           = 1
  actions_enabled     = true
  alarm_actions       = [module.images_api_appautoscaling.scaling_down_policy.arn]

  metric_query {
    id          = "check_thresholds"
    expression  = "(cpu < 10 AND requests_per_target < 40)"
    label       = "CPU utilization and Requests per target limits"
    return_data = true
  }

  metric_query {
    id          = "cpu"
    return_data = false

    metric {
      metric_name = "CPUUtilization"
      namespace   = "AWS/ECS"
      period      = "180"
      stat        = "Average"

      dimensions = {
        ClusterName = data.aws_ecs_cluster.main.cluster_name
        ServiceName = aws_ecs_service.main.name
      }
    }
  }

  metric_query {
    id          = "requests_per_target"
    return_data = false

    metric {
      metric_name = "RequestCountPerTarget"
      namespace   = "AWS/ApplicationELB"
      period      = "180"
      stat        = "Sum"

      dimensions = {
        TargetGroup = aws_lb_target_group.main.arn_suffix
      }
    }
  }
}
