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 backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/ows-store-availability/worker/store-availability-worker-id-348/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
}

data "aws_elasticache_replication_group" "ows_store_availability" {
  replication_group_id = "${var.environment}-ows-store-availability"
}

module "secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.3.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
}

# Run once a minute for general usage. Target tracking is used to scale task provisioning in response to SQS queue depth
module "store_availability_worker_id_348_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.5.1"

  providers = {
    aws.dns = aws.networking
  }

  environment          = var.environment
  service_name         = var.service_name
  application_family   = var.application_family
  aws_region           = var.aws_region
  non_ecr_image        = "${data.aws_caller_identity.current.account_id}.dkr.ecr.${var.aws_region}.amazonaws.com/store-availability-worker:latest"
  commit_sha           = "latest"
  container_port       = "8080"
  task_type            = "worker"
  desired_task_count   = 2
  task_cpu             = 1024
  task_memory          = 2048
  maximum_capacity     = 4
  minimum_capacity     = 0
  vpc_id               = module.vpc_info.vpc_id
  health_check_command = "pgrep python"
  iam_managed_policy_attachments = [
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/SQS-qa-store-availability-Read-Delete",
    "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/Dynamo-qa-ows-store-availability-owsrequest"
  ]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_LEVEL = "INFO"
    },
    {
      DATADOG_ENV = var.environment
    },
    {
      DD_TRACE_ANALYTICS_ENABLED = "true"
    },
    {
      DD_LOGS_INJECTION = "true"
    },
    {
      MYSQL_DATABASE = "ows_store_availability"
    },
    {
      MYSQL_HOST = "qa-ows-store-availability.cluster-cb22xqmk0y0q.us-east-1.rds.amazonaws.com"
    },
    {
      MYSQL_USER = "ows_store_avail"
    },
    {
      REDIS_DB = "0"
    },
    {
      REDIS_HOST = data.aws_elasticache_replication_group.ows_store_availability.primary_endpoint_address
    },
    {
      REDIS_PORT = "6379"
    },
    {
      STORE_ID = "348"
    },
    {
      ITUNES_CMD_BIN = "dummy"
    },
    {
      ITUNES_PASSWORD = "dummy"
    },
    {
      ITUNES_USER = "dummy"
    },
    {
      SPOTIFY_CLIENT_ID = "dummy"
    },
    {
      SPOTIFY_CLIENT_SECRET = "dummy"
    },
  ]

  secrets = [
    {
      MYSQL_PASSWORD = "${var.environment}/${var.service_name}/MYSQL_PASSWORD"
    },
    {
      SENTRY_DSN = "${var.environment}/${var.service_name}/SENTRY_DSN"
    },
  ]
}

# 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}-store-availability-polling-348-message-alarm"
  alarm_description = "SQS-${var.environment}-store-availability-polling-348-message-alarm"
  namespace         = "AWS/SQS"
  metric_name       = "ApproximateNumberOfMessagesVisible"
  statistic         = "Maximum"

  dimensions = {
    QueueName = "${var.environment}-store-availability-polling-348"
  }

  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.store_availability_worker_id_348_fargate_environment]
}

resource "aws_appautoscaling_policy" "scale_down_policy" {
  name               = "${var.environment}-${var.service_name}-sqs-scale-down-policy"
  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.store_availability_worker_id_348_fargate_environment]
}

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

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

  healthy_tasks_monitor_enabled = false
  service_5xx_monitor_enabled   = false
  service_cpu_monitor_enabled   = false

  notification_endpoints            = ""
  escalation_notification_endpoints = ""
}
