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.region

  default_tags {
    tags = module.default_tags.tags
  }
}

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

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/graphql-gateway/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
}

data "aws_acm_certificate" "theorchard_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

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

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

  providers = {
    aws.dns = aws.networking
  }

  environment                              = var.environment
  service_name                             = var.service_name
  application_family                       = var.application_family
  aws_region                               = var.region
  commit_sha                               = "latest"
  container_port                           = "8080"
  task_type                                = "web_service"
  desired_task_count                       = 6
  task_cpu                                 = 4096
  task_memory                              = var.task_memory
  maximum_capacity                         = 32
  minimum_capacity                         = 6
  scaling_cpu_target_value                 = 50
  route53_zone_id                          = data.aws_route53_zone.route53_zone.zone_id
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  vpc_id                                   = module.vpc_info.vpc_id
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]

  fargate_service_subnets = module.vpc_info.default_private_subnet_ids

  load_balancer_subnets = module.vpc_info.default_private_subnet_ids

  https_listener_allow_prefix_list_names = [
    "shared-orcd-jump-box-private-subnet-prefix-list",
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      NODE_ENV = var.environment
    },
    {
      LOGGER_DSN = "https://${var.environment}-fluentd-applications.theorchard.io:8888/application"
    },
    {
      APOLLO_ENGINE_SCHEMA_TAG = var.environment
    },
    {
      AUTH0_DOMAIN = "workstation.auth0.com"
    },
    {
      INTROSPECTION = var.introspection
    },
    {
      NODE_OPTIONS = "--max-old-space-size=${var.task_memory - var.datadog_memory - var.fluentbit_memory}"
    },
    {
      DD_LOGS_INJECTION = true
    },
    {
      SENTRY_DSN = module.sentry_graphql_gateway_prod.sentry_key_dsn_public_output
    },
  ]

  secrets = [
    {
      APOLLO_ENGINE_API_KEY = "${var.environment}/${var.service_name}/APOLLO_ENGINE_API_KEY"
    }
  ]
}

resource "aws_cloudwatch_metric_alarm" "graphql_gateway_response_time" {
  alarm_name        = "${var.environment}-graphql-gateway-response-time-alarm"
  alarm_description = "${var.environment}-graphql-gateway-response-time-alarm"

  namespace          = "AWS/ApplicationELB"
  metric_name        = "TargetResponseTime"
  extended_statistic = "p90"

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

  alarm_actions             = [aws_appautoscaling_policy.scale_up_policy.arn]
  insufficient_data_actions = []

  dimensions = {
    LoadBalancer = module.graphql_gateway_fargate_environment.fargate_load_balancer_arn_suffix
  }
}

resource "aws_appautoscaling_policy" "scale_up_policy" {
  name               = "${var.environment}-${var.service_name}-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.graphql_gateway_fargate_environment]
}

module "secrets" {
  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 "graphql_gateway_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
  datadog_service_type              = "${var.service_name}-graphql"
  datadog_service_name              = "graphql.execute"
  critical_number_5xx               = var.critical_number_5xx
  critical_recovery_number_5xx      = var.critical_recovery_number_5xx
  warning_number_5xx                = var.warning_number_5xx
  warning_recovery_number_5xx       = var.warning_recovery_number_5xx
  notification_endpoints            = var.application_alert_channel
  escalation_notification_endpoints = var.application_alert_channel
  additional_tags                   = { service_type = "critical" }
  dependent_applications            = var.dependent_applications
}

module "sentry_graphql_gateway_prod" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=4.1.2"

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family
  teams              = [var.environment]
}
