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 = 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 backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/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.0.2"

  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=6.1.1"

  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
  maximum_capacity                      = 24
  minimum_capacity                      = 3 # Minimum capacity is set to 3 since we produce 3 derived assets per upload: WAV, FLAC, and MP3_192.
  vpc_id                                = module.vpc_info.vpc_id
  fargate_service_subnets               = module.vpc_info.default_private_subnet_ids
  health_check_command                  = "pgrep python"
  task_protection_policy_enabled        = true
  autoscaling_cpu_policy_enabled        = false
  external_autoscaling_policy_enabled   = true
  fargate_capacity_provider_base        = 3
  fargate_capacity_provider_weight      = 1
  fargate_spot_capacity_provider_weight = 3
  force_new_deployment                  = true
  task_placement_failure_alert_enabled  = true

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


  environment_variables = [
    {
      Environment = var.environment
    },
    {
      AWS_DEFAULT_REGION = var.aws_region
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      SQS_NUM_MESSAGES_TO_PROCESS = "100"
    },
    {
      SQS_TRANSCODING_URL = module.transcoding_jobs_sqs.queue_url
    },
    {
      SQS_MESSAGE_VISIBILITY_TIMEOUT = "120"
    },
    {
      SENTRY_DSN = module.daemon_transcoding_sentry.sentry_key_dsn_public_output
    },
  ]
}

# Configure alarm based on number of messages in specified SQS queue being greater than 0
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
  healthy_tasks_monitor_enabled = false
  service_cpu_monitor_enabled   = false

  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.escalation_notification_endpoints
}

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             = "qa-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]
}
