# Autoscaling for audio services
resource "aws_cloudwatch_metric_alarm" "sqs_audio_queue_visible_messages_scale_up" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  alarm_name        = "SQS-${var.environment}-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-up-alarm"
  alarm_description = "SQS-${var.environment}-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-up-alarm"

  metric_query {
    id          = "total"
    expression  = <<-EOT
      SUM(
        SEARCH(
          '{AWS/SQS,QueueName} MetricName="ApproximateNumberOfMessagesVisible" QueueName=${var.environment}-encoding${var.audio_encoder_id}_e${format("%07d", each.value.encoding_priority)}_d',
          'Maximum',
          60
        )
      )
    EOT
    label       = "Total Visible Messages"
    period      = 60
    return_data = true
  }

  comparison_operator = "GreaterThanThreshold"
  threshold           = 100
  evaluation_periods  = 1

  alarm_actions             = [aws_appautoscaling_policy.audio_scale_up_policy[each.key].arn]
  insufficient_data_actions = []
  ok_actions                = []
}

resource "aws_appautoscaling_policy" "audio_scale_up_policy" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  name               = "${var.environment}-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-sqs-scale-up-policy"
  policy_type        = "StepScaling"
  service_namespace  = "ecs"
  resource_id        = "service/${module.vector_encoder_audio_ecs_service[each.key].fargate_cluster_name}/${module.vector_encoder_audio_ecs_service[each.key].fargate_worker_service_name}"
  scalable_dimension = "ecs:service:DesiredCount"

  step_scaling_policy_configuration {
    adjustment_type         = "ChangeInCapacity"
    cooldown                = var.scaling_cooldown_period_seconds
    metric_aggregation_type = "Maximum"

    step_adjustment {
      metric_interval_lower_bound = 0
      scaling_adjustment          = var.audio_scale_up_adjustment
    }
  }
}

resource "aws_cloudwatch_metric_alarm" "sqs_audio_queue_visible_messages_scale_down" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  alarm_name        = "SQS-${var.environment}-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-down-alarm"
  alarm_description = "SQS-${var.environment}-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-down-alarm"

  metric_query {
    id          = "total"
    expression  = <<-EOT
      SUM(
        SEARCH(
          '{AWS/SQS,QueueName} MetricName="ApproximateNumberOfMessagesVisible" QueueName=${var.environment}-encoding${var.audio_encoder_id}_e${format("%07d", each.value.encoding_priority)}_d',
          'Maximum',
          60
        )
      )
    EOT
    label       = "Total Visible Messages"
    period      = 60
    return_data = true
  }

  comparison_operator = "LessThanOrEqualToThreshold"
  threshold           = 100
  evaluation_periods  = 10

  alarm_actions             = [aws_appautoscaling_policy.audio_scale_down_policy[each.key].arn]
  insufficient_data_actions = []
  ok_actions                = []
}

resource "aws_appautoscaling_policy" "audio_scale_down_policy" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  name               = "${var.environment}-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-sqs-scale-down-policy"
  policy_type        = "StepScaling"
  service_namespace  = "ecs"
  resource_id        = "service/${module.vector_encoder_audio_ecs_service[each.key].fargate_cluster_name}/${module.vector_encoder_audio_ecs_service[each.key].fargate_worker_service_name}"
  scalable_dimension = "ecs:service:DesiredCount"

  step_scaling_policy_configuration {
    adjustment_type         = "ChangeInCapacity"
    cooldown                = var.scaling_cooldown_period_seconds
    metric_aggregation_type = "Maximum"

    step_adjustment {
      metric_interval_upper_bound = 0
      scaling_adjustment          = var.audio_scale_down_adjustment
    }
  }
}

# Autoscaling for video services
resource "aws_cloudwatch_metric_alarm" "sqs_video_queue_visible_messages_scale_up" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  alarm_name        = "SQS-${var.environment}-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-up-alarm"
  alarm_description = "SQS-${var.environment}-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-up-alarm"

  metric_query {
    id          = "total"
    expression  = <<-EOT
      SUM(
        SEARCH(
          '{AWS/SQS,QueueName} MetricName="ApproximateNumberOfMessagesVisible" QueueName=${var.environment}-encoding${var.video_encoder_id}_e${format("%07d", each.value.encoding_priority)}_d',
          'Maximum',
          60
        )
      )
    EOT
    label       = "Total Visible Messages"
    period      = 60
    return_data = true
  }

  comparison_operator = "GreaterThanThreshold"
  threshold           = 0
  evaluation_periods  = 1

  alarm_actions             = [aws_appautoscaling_policy.video_scale_up_policy[each.key].arn]
  insufficient_data_actions = []
  ok_actions                = []
}

resource "aws_appautoscaling_policy" "video_scale_up_policy" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  name               = "${var.environment}-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-sqs-scale-up-policy"
  policy_type        = "StepScaling"
  service_namespace  = "ecs"
  resource_id        = "service/${module.vector_encoder_video_ecs_service[each.key].fargate_cluster_name}/${module.vector_encoder_video_ecs_service[each.key].fargate_worker_service_name}"
  scalable_dimension = "ecs:service:DesiredCount"

  step_scaling_policy_configuration {
    adjustment_type         = "ChangeInCapacity"
    cooldown                = var.scaling_cooldown_period_seconds
    metric_aggregation_type = "Maximum"

    step_adjustment {
      metric_interval_lower_bound = 0
      scaling_adjustment          = var.video_scale_up_adjustment
    }
  }
}

# Autoscaling for video services
resource "aws_cloudwatch_metric_alarm" "sqs_video_queue_visible_messages_scale_down" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  alarm_name        = "SQS-${var.environment}-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-down-alarm"
  alarm_description = "SQS-${var.environment}-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-visible-message-scale-down-alarm"

  metric_query {
    id          = "total"
    expression  = <<-EOT
      SUM(
        SEARCH(
          '{AWS/SQS,QueueName} MetricName="ApproximateNumberOfMessagesVisible" QueueName=${var.environment}-encoding${var.video_encoder_id}_e${format("%07d", each.value.encoding_priority)}_d',
          'Maximum',
          60
        )
      )
    EOT
    label       = "Total Visible Messages"
    period      = 60
    return_data = true
  }

  comparison_operator = "LessThanOrEqualToThreshold"
  threshold           = 0
  evaluation_periods  = 10

  alarm_actions             = [aws_appautoscaling_policy.video_scale_down_policy[each.key].arn]
  insufficient_data_actions = []
  ok_actions                = []
}

resource "aws_appautoscaling_policy" "video_scale_down_policy" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  name               = "${var.environment}-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-sqs-scale-down-policy"
  policy_type        = "StepScaling"
  service_namespace  = "ecs"
  resource_id        = "service/${module.vector_encoder_video_ecs_service[each.key].fargate_cluster_name}/${module.vector_encoder_video_ecs_service[each.key].fargate_worker_service_name}"
  scalable_dimension = "ecs:service:DesiredCount"

  step_scaling_policy_configuration {
    adjustment_type         = "ChangeInCapacity"
    cooldown                = 30
    metric_aggregation_type = "Maximum"

    step_adjustment {
      metric_interval_upper_bound = 0
      scaling_adjustment          = var.video_scale_down_adjustment
    }
  }
}
