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.debezium_source_service_name
  team_name          = "abacus"
}

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/royalty-accounting/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

data "aws_msk_cluster" "kafka_infra" {
  cluster_name = "${var.environment}-${var.msk_cluster_name}"
}

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 "kafka_debezium_source_fargate_environment_royalty_accounting" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=6.4.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         = 1
  task_cpu                 = 1024
  task_memory              = 4096
  container_port           = 8083
  # datadog agent crashes due to OutOfMemoryError with JMX. So increase it from 256
  datadog_task_memory = 512

  blocking_waf_enabled = true

  autoscaling_cpu_policy_enabled           = false
  autoscaling_memory_policy_enabled        = false
  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_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 = var.connector_type
    },
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      CONNECT_BOOTSTRAP_SERVERS = data.aws_msk_cluster.kafka_infra.bootstrap_brokers_tls
    },
    {
      CONNECT_GROUP_UNIQUE_IDENTIFIER = var.db_name
    },
    {
      SNAPSHOT_MODE = "no_data"
    },
    {
      SNAPSHOT_LOCKING_MODE = "none"
    },
    {
      DATABASE_SERVER_NAME = var.db_server_name
    },
    {
      DATABASE_TIMEZONE = "UTC"
    },
    {
      DATABASE_SERVER_ID = "371517767"
    },
    {
      DATABASE_INCLUDE_LIST = var.db_name
    },
    {
      TABLE_INCLUDE_LIST = join(",", [
        "royalty_accounting.contract_term_condition",
        "royalty_accounting.contract_exclusion",
        "royalty_accounting.abacus_outbox"
      ])
    },
    {
      SERVICE_NAME = var.debezium_source_service_name
    },
    {
      SECRETS_MANAGER_DB_KEY = var.db_password_secret_name
    },
    {
      DB_HOST = var.db_host
    },
    {
      DB_PORT = "3306"
    },
    {
      DB_USER = "debezium-ra"
    },
    {
      AWS_REGION = "us-east-1"
    },
    {
      TOPIC_CUSTOM_PREFIX = "cdc"
    },
    {
      CHANGE_TOPIC_CASE_FROM = "LOWER_UNDERSCORE"
    },
    {
      CHANGE_TOPIC_CASE_TO = "LOWER_CAMEL"
    }
  ]
}

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_royalty_accounting.fargate_security_group_id
  self              = true
  type              = "ingress"
}

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

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

  notification_endpoints            = "@slack-abacus-monitoring-qa"
  escalation_notification_endpoints = "@slack-kafka-data-highway-alerts"
  connector_type                    = "debezium_source"

  monitor_kafka_topics = [
    "cdc.royaltyAccounting.contractTermCondition",
    "cdc.royaltyAccounting.contractExclusion",
    "cdc.royaltyAccounting.abacusOutbox"
  ]
  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       = 10
  healthy_tasks_evaluation_window            = "last_1h"
  service_cpu_time_window                    = "last_1h"
  seconds_since_last_event_no_data_timeframe = 40
  seconds_since_last_event_critical          = 500
  seconds_since_last_event_warning           = 200
  # Alert on the number of times the metric shows unhealthy tasks within the last hour
  healthy_tasks_critical_number = 5
}

module "connector_secrets" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"

  environment        = var.environment
  service_name       = var.debezium_source_service_name
  secret_name        = var.db_password_secret_name
  application_family = var.application_family
}
