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

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.aws_region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

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

data "aws_caller_identity" "current" {}

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

  environment = var.environment
}

# Run once a minute for general usage. Target tracking is used to scale task provisioning in response to SQS queue depth
module "daemon_transcoding_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
  service_platform_version = "1.4.0"
  commit_sha               = "latest"
  container_port           = "8080"
  task_type                = "worker"
  desired_task_count       = 4
  task_cpu                 = 1024
  task_memory              = 2048
  maximum_capacity         = 144
  # Don't scale down to zero even when the queue is empty, to ensure that new work starts processing immediately
  minimum_capacity                    = 9
  vpc_id                              = module.vpc_info.vpc_id
  fargate_service_subnets             = ["subnet-098b89d0c58c5693a", "subnet-067a6b45b079d7296", "subnet-043d235081c966332"]
  health_check_command                = "pgrep python"
  task_protection_policy_enabled      = true
  autoscaling_cpu_policy_enabled      = false
  external_autoscaling_policy_enabled = true

  iam_managed_policy_attachments = [
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-prod-orcd-transcoded-assets-RW",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/SQS-prod-transcoding-jobs-RW",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-prod-orcd-mezzanine-assets-RW",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-prod-orcd-raw-assets-Read-Get",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/S3-prod-orcd-raw-assets-PutItem",
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      AWS_DEFAULT_REGION = var.aws_region
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      DEBUG = "1"
    },
    {
      SQS_NUM_MESSAGES_TO_PROCESS = "500" # Setting this high to reduce task churn (since we never scale to zero tasks), which leads to high AWS Config costs
    },
    {
      SQS_TRANSCODING_URL = "https://sqs.${var.aws_region}.amazonaws.com/${data.aws_caller_identity.current.account_id}/${var.environment}-transcoding-jobs"
    },
    {
      SQS_MESSAGE_VISIBILITY_TIMEOUT = "600"
    },
    {
      SENTRY_DSN = module.daemon_transcoding_sentry.sentry_key_dsn_public_output
    },
  ]
}

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

  dimensions = {
    QueueName = "${var.environment}-transcoding-jobs"
  }

  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
    metric_aggregation_type = "Maximum"

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

  depends_on = [module.daemon_transcoding_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
    metric_aggregation_type = "Maximum"

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

  depends_on = [module.daemon_transcoding_fargate_environment]
}

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

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

  application_family                = var.application_family
  service_4xx_monitor_enabled       = false
  service_5xx_monitor_enabled       = false
  service_cpu_monitor_enabled       = false
  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.escalation_notification_endpoints
  healthy_tasks_evaluation_window   = "last_30m"
}

module "transcoding_jobs_sqs" {
  source = "git@github.com:theorchard/terraform-sqs.git//?ref=2.5.0"

  environment                   = var.environment
  application_family            = var.application_family
  custom_queue_name             = "prod-transcoding-jobs"
  sqs_max_message_size          = 1048576
  sqs_message_retention_seconds = 345600
  sqs_delay_seconds             = 0
  sqs_receive_wait_time_seconds = 0
}

module "daemon_transcoding_sentry" {
  source             = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"
  service_name       = var.service_name
  environment        = var.environment
  application_family = var.application_family
  platform           = "python"
  teams              = [var.environment]
}
