locals {
  splitted_arn = try(split(":", module.daemon_youtube_ownership_sqs_queue.deadletter_queue_arn), [])
  dlq_name     = try(element(local.splitted_arn, length(local.splitted_arn) - 1), "")
}

module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = var.team_name
}

provider "aws" {
  region = "us-east-1"

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = "us-east-1"
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/daemon-youtube-ownership/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.1.0"

  environment = var.environment
}

data "aws_route53_zone" "route53_zone" {
  name = "theorchard.io"
}

# we can potentially use the policy arn from the module output,
# however not all actions enabled in the policy is present in the policy created in the module
data "aws_iam_policy" "daemon_youtube_ownership_deadletter_access_policy" {
  name = "SQS-${var.environment}-yt-ownership-Read-Delete"
}

module "daemon_youtube_ownership_owsrequest" {
  source           = "git@github.com:theorchard/terraform-owsrequest.git//?ref=1.1.0"
  environment_name = var.environment
  service_name     = var.service_name
}

module "daemon_youtube_ownership_sqs_queue" {
  source             = "git@github.com:theorchard/terraform-sqs.git//?ref=2.4.1"
  environment        = var.environment
  custom_queue_name  = "${var.environment}-yt-ownership-1"
  application_family = var.application_family

  # those are the current values
  sqs_deadletter_enabled         = true
  sqs_delay_seconds              = 0
  sqs_max_message_size           = 262144
  sqs_message_retention_seconds  = 1209600
  sqs_receive_wait_time_seconds  = 20
  sqs_visibility_timeout_seconds = 60
  deadletter_max_message_size    = 2048

  # 14 days
  deadletter_message_retention_seconds = 1209600
}

module "multiple_secrets_with_same_settings" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.secrets_manager_secret_names)

  environment                    = var.environment
  service_name                   = var.service_name
  secret_name                    = each.value
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

module "daemon_youtube_ownership_rds" {
  source = "git@github.com:theorchard/terraform-rds.git//?ref=6.6.0"

  providers = {
    aws.dns = aws.networking
  }

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family

  rds_master_username = "daemon_youtube_ownership_admin"
  rds_master_password = "s0mePass!changme"

  rds_cluster_instance_class                = "db.t4g.medium"
  rds_cluster_instance_count                = "1"
  rds_db_cluster_parameter_group_name       = "aurora-mysql80sync"
  rds_cluster_instance_parameter_group_name = "default.aurora-mysql8.0"
  rds_engine                                = "aurora-mysql"
  rds_engine_version                        = "8.0.mysql_aurora.3.10.3"
  rds_db_subnet_group_name                  = "prod-orchard-private-subnet-group"
  rds_availability_zones                    = ["us-east-1a", "us-east-1c"]
  rds_performance_insights_enabled          = true
  enabled_cloudwatch_logs_exports           = ["audit", "error", "general"]
  vpc_id                                    = module.vpc_info.vpc_id
  route53_zone_id                           = data.aws_route53_zone.route53_zone.zone_id
}

module "daemon_youtube_ownership_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.6.0"

  providers = {
    aws.dns = aws.networking
  }

  application_family                  = var.application_family
  environment                         = var.environment
  service_name                        = var.service_name
  aws_region                          = var.aws_region
  commit_sha                          = "latest"
  container_port                      = "8080"
  task_type                           = "worker"
  task_cpu                            = 1024
  task_memory                         = 2048
  autoscaling_cpu_policy_enabled      = false
  autoscaling_memory_policy_enabled   = false
  external_autoscaling_policy_enabled = true
  desired_task_count                  = 2
  minimum_capacity                    = 2
  maximum_capacity                    = var.maximum_capacity
  vpc_id                              = module.vpc_info.vpc_id

  iam_managed_policy_attachments = [
    module.daemon_youtube_ownership_owsrequest.policy_arn_output,
    data.aws_iam_policy.daemon_youtube_ownership_deadletter_access_policy.arn
  ]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      DATADOG_ENV = "${var.environment}-${var.service_name}"
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      AWS_REGION = var.aws_region
    },
    {
      QUEUE_READER_THREADS = "1"
    },
    {
      API_EXECUTOR_THREADS = "1"
    },
    {
      API_RATE_LIMIT = "1000"
    },
    {
      TRACK_SUCCESSES = "0"
    },
    {
      DEBUG = "1"
    },
    {
      LOGGER_DSN = "https://${var.environment}-fluentd-applications.theorchard.io:8888/application"
    }
  ]
  secrets = [
    {
      DB_CONNECTION_STRING = "${var.environment}/${var.service_name}/DB_CONNECTION_STRING"
    },
    {
      SENTRY_DSN = "${var.environment}/${var.service_name}/SENTRY_DSN"
    },
    {
      GOOGLE_API_KEY = "${var.environment}/${var.service_name}/GOOGLE_API_KEY"
    },
  ]
}

resource "aws_cloudwatch_metric_alarm" "sqs_queue_visible_messages" {
  alarm_name        = "SQS-${var.environment}-yt-ownership-1-visible-message-alarm"
  alarm_description = "SQS-${var.environment}-yt-ownership-1-visible-message-alarm"
  namespace         = "AWS/SQS"
  metric_name       = "ApproximateNumberOfMessagesVisible"
  statistic         = "Maximum"

  dimensions = {
    QueueName = "${var.environment}-yt-ownership-1"
  }

  comparison_operator = "GreaterThanThreshold"
  threshold           = 0
  period              = 60
  evaluation_periods  = 1

  alarm_actions             = [aws_appautoscaling_policy.scale_up_policy.arn]
  insufficient_data_actions = []
  ok_actions                = [aws_appautoscaling_policy.scale_down_policy.arn]
}

resource "aws_appautoscaling_policy" "scale_up_policy" {
  name               = "${var.environment}-${var.service_name}-sqs-scale-up-policy"
  policy_type        = "StepScaling"
  service_namespace  = "ecs"
  resource_id        = "service/${var.environment}-${var.service_name}/${var.environment}-${var.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.scale_up_adjustment
    }
  }

  depends_on = [module.daemon_youtube_ownership_fargate_environment]
}

resource "aws_appautoscaling_policy" "scale_down_policy" {
  name               = "${var.environment}-${var.service_name}-sqs-scale-down-policy"
  policy_type        = "StepScaling"
  service_namespace  = "ecs"
  resource_id        = "service/${var.environment}-${var.service_name}/${var.environment}-${var.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.scale_down_adjustment
    }
  }

  depends_on = [module.daemon_youtube_ownership_fargate_environment]
}

module "fargate_service_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.13.4"

  environment        = var.environment
  environment_type   = "fargate"
  service_name       = var.service_name
  application_family = var.application_family

  service_5xx_monitor_enabled       = true
  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.notification_endpoints
}

module "daemon_youtube_ownership_rds_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/rds?ref=6.13.4"

  application_family = var.application_family
  environment        = var.environment
  service_name       = var.service_name

  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.notification_endpoints
}
resource "datadog_monitor" "youtube_daemon_queue" {
  name    = "${var.environment}-${var.youtube_daemon_queue_monitor}"
  type    = "metric alert"
  message = "Running https://pipeline.theorchard.io/job/fargate-redeploy with PROD + daemon-youtube-ownership usually fixes this if its stuck. More info at https://www.notion.so/Outages-Error-Alerts-Runbook-1e797177520f80b798a9c3f5f51bff6a. Notify: ${var.escalation_notification_endpoints}"

  query = "avg(last_1h):max:aws.sqs.approximate_number_of_messages_visible{queuename:${var.environment}-yt-ownership-1} > 15000"

  monitor_thresholds {
    critical = 15000
  }

  renotify_interval   = 60    // minutes
  require_full_window = false // DD recommends setting to false for sparse metrics

  tags = [
    "environment:${var.environment}",
    "service_name:${var.service_name}",
    "application_family:${var.application_family}",
  ]
}

resource "datadog_monitor" "youtube_daemon_dlq" {
  name            = "${var.environment}-${var.youtube_daemon_dlq_monitor}"
  type            = "metric alert"
  on_missing_data = "default"
  message         = "Bad messages encountered in SQS queue **prod-yt-ownership-1-deadletter**. Please investigate. Processing is not blocked. More info at https://www.notion.so/Outages-Error-Alerts-Runbook-1e797177520f80b798a9c3f5f51bff6a. Notify: ${var.notification_endpoints}"

  query = "avg(last_1h):max:aws.sqs.approximate_number_of_messages_visible{queuename:${local.dlq_name}} > 1"

  monitor_thresholds {
    critical = 1
  }

  renotify_interval   = 60    // minutes
  require_full_window = false // DD recommends setting to false for sparse metrics

  tags = [
    "environment:${var.environment}",
    "service_name:${var.service_name}",
    "application_family:${var.application_family}",
  ]
}
