# Log groups =================================================================

resource "aws_cloudwatch_log_group" "this" {
  for_each = var.log_groups

  name              = each.value.name
  retention_in_days = each.value.retention_in_days
  kms_key_id        = each.value.kms_key_id
  skip_destroy      = each.value.skip_destroy

  tags = local.tags
}

# Metric filters -------------------------------------------------------------

resource "aws_cloudwatch_log_metric_filter" "this" {
  for_each = var.metric_filters

  name           = each.key
  log_group_name = aws_cloudwatch_log_group.this[each.value.log_group_key].name
  pattern        = each.value.pattern

  metric_transformation {
    name          = each.value.metric_name
    namespace     = each.value.metric_namespace
    value         = each.value.metric_value
    default_value = each.value.default_value
  }
}

# Metric alarms ==============================================================

resource "aws_cloudwatch_metric_alarm" "this" {
  for_each = var.alarms

  alarm_name          = each.value.alarm_name
  alarm_description   = each.value.alarm_description
  namespace           = each.value.namespace
  metric_name         = each.value.metric_name
  statistic           = each.value.statistic
  period              = each.value.period
  evaluation_periods  = each.value.evaluation_periods
  threshold           = each.value.threshold
  comparison_operator = each.value.comparison_operator
  treat_missing_data  = each.value.treat_missing_data
  datapoints_to_alarm = each.value.datapoints_to_alarm
  alarm_actions       = each.value.alarm_actions
  ok_actions          = each.value.ok_actions
  dimensions          = each.value.dimensions

  tags = local.tags
}

# Composite alarms -----------------------------------------------------------

resource "aws_cloudwatch_composite_alarm" "this" {
  for_each = var.composite_alarms

  alarm_name        = each.value.alarm_name
  alarm_description = each.value.alarm_description
  alarm_rule        = each.value.alarm_rule
  alarm_actions     = each.value.alarm_actions
  ok_actions        = each.value.ok_actions

  tags = local.tags
}

# Dashboards =================================================================

resource "aws_cloudwatch_dashboard" "this" {
  for_each = var.dashboards

  dashboard_name = each.key
  dashboard_body = each.value
}
