# General variables
variable "environment" {
  description = "Name of the environment, e.g. dev, qa, prod"
  default     = "dev"
}

variable "environment_type" {
  description = "Type of environment: valid options are fargate"
  default     = "fargate"
}

variable "service_name" {
  description = "Service name, without environment prefix"
  default     = "ows-service"
}

variable "application_family" {
  type        = string
  description = "Application family to which this service belongs"
}

variable "teams" {
  type        = set(string)
  description = "A set of Datadog Teams to associate the resources with"
  default     = []
}

variable "additional_tags" {
  type        = map(string)
  description = "Optional map of additional tags to set on resources. These will be combined with programmatically set required tags."
  default     = {}
}

variable "dependent_applications" {
  type        = set(string)
  description = "Optional list of dependent applications to set as a dependent_application tag on resources. These will be combined with programmatically set required tags."
  default     = []
}

variable "notification_endpoints" {
  description = "Endpoints for all alerts. Can be email, slack, pagerduty, etc"
}

variable "escalation_notification_endpoints" {
  description = "Endpoints for escalation alerts. Can be email, slack, pagerdut, etc"
}

variable "alert_notification_endpoints" {
  type        = string
  description = "Additional endpoints to send only alert notifications to. Can be email, slack, pagerduty, etc."
  default     = ""
}

variable "no_data_notification_endpoints" {
  type        = string
  description = "Additional endpoints to send only no data notifications to. Can be email, slack, pagerduty, etc."
  default     = ""
}

# AWS variables
variable "aws_region" {
  description = "AWS region from which to pull metrics"
  default     = "us-east-1"
}

variable "timeseries_dashboard_enabled" {
  description = "Wether or not timeseries dashboard is enabled"
  default     = true
}

variable "screen_dashboard_enabled" {
  description = "Wether or not screen dashboard is enabled"
  default     = true
}

# Monitor variables
variable "service_5xx_monitor_enabled" {
  description = "Whether or not 5xx monitor is enabled"
  default     = true
}

variable "service_5xx_monitor_silenced" {
  description = "Whether or not 5xx monitor is silenced (creates a 'datadog_downtime_schedule' resource)"
  default     = false
}

variable "critical_number_5xx" {
  description = "Number of 5xx requests (per 5m) for critical alerts"
  default     = 10
}

variable "critical_recovery_number_5xx" {
  description = "Number of 5xx requests (per 5m) for critical recovery"
  default     = 5
}

variable "warning_number_5xx" {
  description = "Number of 5xx requests (per 5m) for warnings"
  default     = 5
}

variable "warning_recovery_number_5xx" {
  description = "Number of 5xx requests (per 5m) for warning recovery"
  default     = 2
}

variable "ok_number_5xx" {
  description = "Number of 5xx requests (per 5m) that are ok"
  default     = 2
}

variable "notification_overrides_5xx" {
  description = "Override the notification settings for the 5xx monitor. Note if this is specified then the notification settings for the monitor will be determined solely by this variable - no settings will be inherited from the defaults."
  type = object({
    endpoints            = string
    escalation_endpoints = string
    alert_endpoints      = optional(string, "")
    no_data_endpoints    = optional(string, "")
  })
  default = null
}

variable "service_4xx_monitor_enabled" {
  description = "Whether or not 4xx monitor is enabled"
  default     = false
}

variable "service_4xx_monitor_silenced" {
  description = "Whether or not 4xx monitor is silenced (creates a 'datadog_downtime_schedule' resource)"
  default     = false
}

variable "critical_number_4xx" {
  description = "Number of 4xx requests (per 5m) for critical alerts"
  default     = 20
}

variable "critical_recovery_number_4xx" {
  description = "Number of 4xx requests (per 5m) for critical recovery"
  default     = 15
}

variable "warning_number_4xx" {
  description = "Number of 4xx requests (per 5m) for warnings"
  default     = 10
}

variable "warning_recovery_number_4xx" {
  description = "Number of 4xx requests (per 5m) for warning recovery"
  default     = 5
}

variable "ok_number_4xx" {
  description = "Number of 4xx requests (per 5m) that are ok"
  default     = 2
}

variable "notification_overrides_4xx" {
  description = "Override the notification settings for the 4xx monitor. Note if this is specified then the notification settings for the monitor will be determined solely by this variable - no settings will be inherited from the defaults."
  type = object({
    endpoints            = string
    escalation_endpoints = string
    alert_endpoints      = optional(string, "")
    no_data_endpoints    = optional(string, "")
  })
  default = null
}

variable "healthy_tasks_monitor_enabled" {
  description = "Whether or not healthy tasks monitor is enabled"
  default     = true
}

variable "healthy_tasks_monitor_silenced" {
  description = "Whether or not healthy tasks monitor is silenced (creates a 'datadog_downtime_schedule' resource)"
  default     = false
}

variable "healthy_tasks_critical_number" {
  description = "Number of healthy_tasks for critical alerts"
  default     = 0.1
}

variable "healthy_tasks_critical_recovery_number" {
  description = "Number of healthy_tasks for critical recovery"
  default     = 1
}

variable "healthy_tasks_warning_number" {
  description = "Number of healthy_tasks for warnings"
  default     = 1
}

variable "healthy_tasks_warning_recovery_number" {
  description = "Number of healthy_tasks for warning recovery"
  default     = 2
}

variable "healthy_tasks_ok_number" {
  description = "Number of healthy_tasks that are ok"
  default     = 2
}

variable "healthy_tasks_evaluation_window" {
  description = "How long to use for evaluation window"
  default     = "last_5m"
}

variable "healthy_tasks_notification_overrides" {
  description = "Override the notification settings for the healthy tasks monitor. Note if this is specified then the notification settings for the monitor will be determined solely by this variable - no settings will be inherited from the defaults."
  type = object({
    endpoints            = string
    escalation_endpoints = string
    alert_endpoints      = optional(string, "")
    no_data_endpoints    = optional(string, "")
  })
  default = null
}

variable "service_cpu_monitor_enabled" {
  description = "Whether or not service cpu monitor is enabled"
  default     = true
}

variable "service_cpu_monitor_silenced" {
  description = "Whether or not service cpu monitor is silenced (creates a 'datadog_downtime_schedule' resource)"
  default     = false
}

variable "service_cpu_critical_number" {
  description = "CPU utilization percentage (per 5m) for critical alerts"
  default     = 90
}

variable "service_cpu_critical_recovery_number" {
  description = "CPU utilization percentage (per 5m) for critical recovery"
  default     = 85
}

variable "service_cpu_time_window" {
  description = "CPU utilization time window"
  default     = "last_5m"
}

variable "service_cpu_monitor_evaluation_function" {
  description = "CPU utilization evaluation function"
  default     = "avg"

  validation {
    condition     = contains(["avg", "max", "min", "sum"], var.service_cpu_monitor_evaluation_function)
    error_message = "Allowed values for service_cpu_monitor_evaluation_function are \"avg\", \"max\", \"min\", or \"sum\"."
  }
}

variable "service_cpu_warning_number" {
  description = "CPU utilization percentage (per 5m) for warnings"
  default     = 80
}

variable "service_cpu_warning_recovery_number" {
  description = "CPU utilization percentage (per 5m) for warning recovery"
  default     = 75
}

variable "service_cpu_ok_number" {
  description = "CPU utilization percentage (per 5m) that are ok"
  default     = 70
}

variable "service_cpu_notification_overrides" {
  description = "Override the notification settings for the service cpu monitor. Note if this is specified then the notification settings for the monitor will be determined solely by this variable - no settings will be inherited from the defaults."
  type = object({
    endpoints            = string
    escalation_endpoints = string
    alert_endpoints      = optional(string, "")
    no_data_endpoints    = optional(string, "")
  })
  default = null
}

variable "datadog_service_type" {
  description = "Type of service for datadog to monitor"
  default     = "flask"
}

variable "datadog_service_name" {
  description = "Name of service for datadog to monitor"
  default     = "flask.request"
}

# Failed tasks monitor configuration
variable "failed_tasks_monitor_enabled" {
  type        = bool
  description = "Whether or not to enable a monitor for unexpected task stopped events (excludes events where containers exited with a zero exit code)"
  default     = false
}

variable "critical_number_failed_tasks" {
  description = "Number of unexpected stopped task events (per 5m) for critical alerts"
  default     = 2
}

variable "critical_recovery_number_failed_tasks" {
  description = "Number of unexpected stopped task events (per 5m) for critical recovery"
  default     = 1
}

variable "warning_number_failed_tasks" {
  description = "Number of unexpected stopped task events (per 5m) for warnings"
  default     = 1
}

variable "warning_recovery_number_failed_tasks" {
  description = "Number of unexpected stopped task events (per 5m) for warning recovery"
  default     = 0
}

variable "notification_overrides_failed_tasks" {
  description = "Override the notification settings for the failed tasks monitor. Note if this is specified then the notification settings for the monitor will be determined solely by this variable - no settings will be inherited from the defaults."
  type = object({
    endpoints            = string
    escalation_endpoints = string
    alert_endpoints      = optional(string, "")
    no_data_endpoints    = optional(string, "")
  })
  default = null
}

# Successful tasks monitor configuration
variable "successful_tasks_monitor_enabled" {
  type        = bool
  description = "Whether or not to enable a monitor for task stopped events where the task was successful. The primary usecase for this is for monitoring scheduled tasks, in which case the other variables should be set in accordance with the schedule."
  default     = false
}

variable "successful_tasks_query_interval" {
  type        = string
  description = "The query interval to use for the successful tasks monitor. For scheduled tasks, this should be the maximum expected time between successful tasks, which should generally be slightly longer than the scheduling rate"
  default     = "last_1d"
}

variable "successful_tasks_group_by" {
  type        = string
  description = "Optional field to group the successful tasks query by. An alert will be sent for each group."
  default     = null
}

variable "critical_number_successful_tasks" {
  description = "The number of successful tasks in the query interval below which to trigger a critical alert"
  default     = 1
}

variable "critical_recovery_number_successful_tasks" {
  description = "The number of successful tasks in the query interval required to recover from a critical alert"
  default     = null
}

variable "warning_number_successful_tasks" {
  description = "The number of successful tasks in the query interval below which to trigger a warning"
  default     = null
}

variable "warning_recovery_number_successful_tasks" {
  description = "The number of successful tasks in the query interval required to recover from a warning"
  default     = null
}

variable "notification_overrides_successful_tasks" {
  description = "Override the notification settings for the successful tasks monitor. Note if this is specified then the notification settings for the monitor will be determined solely by this variable - no settings will be inherited from the defaults."
  type = object({
    endpoints            = string
    escalation_endpoints = string
    alert_endpoints      = optional(string, "")
    no_data_endpoints    = optional(string, "")
  })
  default = null
}


locals {
  healthy_tasks_filter = {
    fargate          = "servicename:${var.environment}-${var.service_name}"
  }

  healthy_tasks_monitor_metric = {
    fargate          = "aws.ecs.service.running"
  }

  service_cpu_monitor_filter = {
    fargate          = "servicename:${var.environment}-${var.service_name}"
  }

  service_cpu_monitor_metric = {
    fargate          = "aws.ecs.cpuutilization.maximum"
  }

  service_4xx_monitor_metric = {
    fargate          = "aws.applicationelb.httpcode_target_4xx"
  }

  service_5xx_monitor_metric = {
    fargate          = "aws.applicationelb.httpcode_target_5xx"
  }

  service_alb_5xx_monitor_metric = {
    fargate          = "aws.applicationelb.httpcode_elb_5xx"
  }

  # Only team tags are supported for dashboards
  dashboard_tags = [for team in var.teams : "team:${team}"]

  # Concatenate required and user-supplied tags
  combined_resource_tags = flatten(concat(
    [
      "env:${var.environment}",
      "environment:${var.environment}",
      "service:${var.service_name}",
      "service_name:${var.service_name}",
      "application_family:${var.application_family}"
    ],
    [for tag_name, tag_value in var.additional_tags : "${tag_name}:${tag_value}"],
    [for team in var.teams : "team:${team}"],
    [for dependent_application in var.dependent_applications : "dependent_application:${dependent_application}"]
  ))

  default_notification_settings = {
    endpoints            = var.notification_endpoints
    escalation_endpoints = var.escalation_notification_endpoints
    alert_endpoints      = var.alert_notification_endpoints
    no_data_endpoints    = var.no_data_notification_endpoints
  }
}
