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/kafka-infra/debezium_source/content-review/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_acm_certificate" "theorchard_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

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

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

  providers = {
    aws.dns = aws.networking
  }

  environment              = var.environment
  service_name             = var.debezium_source_service_name
  application_family       = var.application_family
  additional_tags          = var.additional_tags
  non_ecr_image            = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/kafka-connect-debezium:latest"
  aws_region               = var.aws_region
  service_platform_version = "1.4.0"
  desired_task_count       = 1
  minimum_capacity         = 1
  maximum_capacity         = 2
  task_cpu                 = 1024
  task_memory              = 3072
  container_port           = 8083
  # datadog agent crashes due to OutOfMemoryError with JMX. So increase it from 256
  datadog_task_memory = 512

  blocking_waf_enabled = true

  health_check_grace_period_seconds        = 180
  container_start_period_seconds           = 180
  health_check_path                        = "/connectors/${var.connector_name}"
  web_service_health_check_command         = "[ \"$(curl -s -f http://localhost:8083/connectors/${var.connector_name}/tasks/0/status | jq -r .state)\" == 'RUNNING' ] || exit 1"
  
  # Fargate SPOT Task, QA only
  force_new_deployment                     = true
  fargate_spot_capacity_provider_weight    = 100
  task_placement_failure_alert_enabled     = true

  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]

  vpc_id                  = module.vpc_info.vpc_id
  fargate_service_subnets = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets   = module.vpc_info.default_private_subnet_ids
  datadog_custom_image    = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/orchard-datadog-agent-jmx:latest"

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

  datadog_agent_environment_variables = [
    {
      JMX_PORT = "9095"
    },
    {
      DD_ENV = var.environment
    },
    {
      SERVICE_NAME = var.debezium_source_service_name
    },
    {
      CONNECTOR_TYPE = "debezium_source"
    },
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      CONNECT_BOOTSTRAP_SERVERS = var.connect_bootstrap_servers
    },
    {
      CONNECT_GROUP_UNIQUE_IDENTIFIER = "debezium_${var.db_name}"
    },
    {
      SNAPSHOT_MODE = "no_data"
    },
    {
      SNAPSHOT_LOCKING_MODE = "none"
    },
    {
      DATABASE_SERVER_NAME = "${var.environment}_${var.db_name}"
    },
    {
      DATABASE_TIMEZONE = "UTC"
    },
    {
      DATABASE_SERVER_ID = var.db_server_id
    },
    {
      DATABASE_INCLUDE_LIST = var.db_name
    },
    {
      TABLE_INCLUDE_LIST = "${var.db_name}.review_queue,${var.db_name}.queue_move_history"
    },
    {
      SERVICE_NAME = var.debezium_source_service_name
    },
    {
      SECRETS_MANAGER_DB_KEY = "DB_PASSWORD"
    },
    {
      DB_HOST = var.db_host
    },
    {
      DB_PORT = "3306"
    },
    {
      DB_USER = "debezium-cr-src"
    },
    {
      AWS_REGION = "us-east-1"
    },
    {
      TOPIC_CUSTOM_PREFIX = "cdc"
    },
    {
      CHANGE_TOPIC_CASE_FROM = "LOWER_UNDERSCORE"
    },
    {
      CHANGE_TOPIC_CASE_TO = "LOWER_CAMEL"
    },
    {
      INCONSISTENT_SCHEMA_HANDLING_MODE = "warn"
    }
  ]
}

resource "aws_security_group_rule" "allow_intra_cluster_communication_cr" {
  from_port         = 8083
  to_port           = 8083
  protocol          = "tcp"
  security_group_id = module.kafka_debezium_source_fargate_environment_content_review.fargate_security_group_id
  self              = true
  type              = "ingress"
}

module "fargate_service_dashboard_content_review" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/kafka_connector?ref=6.15.2"

  environment        = var.environment
  environment_type   = "fargate"
  service_name       = var.debezium_source_service_name
  application_family = var.application_family
  connector_type     = "debezium_source"

  notification_endpoints                     = "@slack-content-review-team"
  escalation_notification_endpoints          = "@slack-kafka-data-highway-alerts"
  monitor_kafka_topics                       = ["cdc.contentReview.reviewQueue", "cdc.contentReview.queueMoveHistory"]
  monitor_kafka_topics_cluster_name          = "qa-managed-kafka-cdc-destination"
  healthy_tasks_monitor_enabled              = true
  service_cpu_monitor_enabled                = true
  error_monitor_enabled                      = true
  error_monitor_critical_number_errors       = 5
  healthy_tasks_evaluation_window            = "last_1h"
  service_cpu_time_window                    = "last_1h"
  seconds_since_last_event_no_data_timeframe = 30
  # Alert on the number of times the metric shows unhealthy tasks within the last hour
  healthy_tasks_critical_number = 5 
}
