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       = local.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/jdbc-sink/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 "service_credentials_secret" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"

  environment                    = var.environment
  application_family             = var.application_family
  additional_tags                = var.additional_tags
  service_name                   = local.service_name
  secret_name                    = "DATABASE_CREDENTIALS"
  secret_recovery_window_in_days = 7
}

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

  providers = {
    aws.dns = aws.networking
  }

  environment                           = var.environment
  application_family                    = var.application_family
  additional_tags                       = var.additional_tags
  service_name                          = local.service_name
  non_ecr_image                         = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/${local.ecr_image_name}: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
  health_check_grace_period_seconds     = 120
  container_start_period_seconds        = 120
  blocking_waf_enabled                  = true
  health_check_path                     = "/connectors/${local.service_name}"
  web_service_health_check_command      = "[[ $(curl -s http://localhost:8083/connectors/${local.service_name}/status | jq -r '.tasks[].state' | sort | uniq) == 'RUNNING' ]] || exit 1"
  fargate_spot_capacity_provider_weight = 100
  task_placement_failure_alert_enabled  = true
  route53_zone_id                       = data.aws_route53_zone.route53_zone.zone_id
  propagate_tags                        = true

  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
  datadog_custom_image  = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/orchard-datadog-agent-jmx:latest"
  # datadog agent crashes due to OutOfMemoryError with JMX. So increase it from 256
  datadog_task_memory = 512
  datadog_agent_environment_variables = [
    {
      JMX_PORT = "9095"
    },
    {
      DD_ENV = var.environment
    },
    {
      SERVICE_NAME = local.service_name
    },
    {
      CONNECTOR_TYPE = "default_sink"
    },
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      CONNECT_GROUP_UNIQUE_IDENTIFIER = local.ecs_cluster_name
    },
    {
      CONNECTOR_NAME = local.service_name
    },
    {
      SERVICE_NAME = local.service_name
    },
    {
      CONNECT_BOOTSTRAP_SERVERS = var.connect_bootstrap_servers
    },
    {
      AWS_SECRETS_MANAGER = "true"
    },
    {
      AWS_REGION = var.aws_region
    },
    {
      KAFKA_TOPICS = join(",", [
        "stream.nrGraph.mysql.nr.sound.recording",
        "stream.nrGraph.mysql.nr.contribution",
        "stream.nrGraph.mysql.nr.contribution.contributed.to.nr.sound.recording",
        "stream.nrGraph.mysql.nr.contributor",
        "stream.nrGraph.mysql.nr.contributor.is.main.performer.nr.contribution",
        "stream.nrGraph.mysql.nr.contributor.is.session.musician.nr.contribution",
        "stream.nrGraph.mysql.nr.contributor.is.featuring.performer.nr.contribution",
      ])
    },
    {
      TOPICS_COMMON_PREFIX = "stream.nrGraph.mysql."
    },
    {
      TOPIC_MAPPING_NR_SOUND_RECORDING = "nr_sound_recording"
    },
    {
      TOPIC_MAPPING_NR_CONTRIBUTION = "nr_contribution"
    },
    {
      TOPIC_MAPPING_NR_CONTRIBUTION_CONTRIBUTED_TO_NR_SOUND_RECORDING = "nr_contribution_contributed_to_nr_sound_recording"
    },
    {
      TOPIC_MAPPING_NR_CONTRIBUTOR = "nr_contributor"
    },
    {
      TOPIC_MAPPING_NR_CONTRIBUTOR_IS_MAIN_PERFORMER_NR_CONTRIBUTION = "nr_contributor_is_main_performer_nr_contribution"
    },
    {
      TOPIC_MAPPING_NR_CONTRIBUTOR_IS_SESSION_MUSICIAN_NR_CONTRIBUTION = "nr_contributor_is_session_musician_nr_contribution"
    },
    {
      TOPIC_MAPPING_NR_CONTRIBUTOR_IS_FEATURING_PERFORMER_NR_CONTRIBUTION = "nr_contributor_is_featuring_performer_nr_contribution"
    },
    {
      DATABASE_CONNECTION_URL = "jdbc:mysql://qa-statementdb.qa-accounting.theorchard.io:3306/stmt-db"
    },
    {
      INSERT_MODE = "upsert"
    },
    {
      PK_MODE = "record_key"
    },
    {
      PK_FIELDS = ""
    },
    {
      DELETE_ENABLED = "true"
    },
    {
      BATCH_SIZE = 3000
    },
    {
      JDBC_KEY_CONVERTER = "io.confluent.connect.avro.AvroConverter"
    },
    {
      JDBC_VALUE_CONVERTER = "io.confluent.connect.avro.AvroConverter"
    },
    {
      JDBC_KEY_CONVERTER_SCHEMAS_ENABLE = "true"
    },
    {
      JDBC_VALUE_CONVERTER_SCHEMAS_ENABLE = "true"
    },
    {
      SCHEMA_REGISTRY_URL = "https://${var.environment}-schema-registry.theorchard.io"
    },
    {
      AUTO_REGISTER_SCHEMAS = "true"
    },
    {
      DLQ_TOPIC_NAME = var.dlq_topic_name
    },
    {
      DEBUG_MODE = "false"
    },
  ]
}

# This rule will allow kafka-connect tasks to communicate with each other in distributed mode
resource "aws_security_group_rule" "allow_intra_cluster_communication_nr" {
  from_port         = 8083
  to_port           = 8083
  protocol          = "tcp"
  security_group_id = module.kafka_jdbc_sink_nr_fargate_environment.fargate_security_group_id
  self              = true
  type              = "ingress"
}

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

  environment        = var.environment
  application_family = var.application_family
  additional_tags    = var.additional_tags
  service_name       = local.service_name
  connector_type     = "default_sink"

  environment_type = "fargate"

  notification_endpoints            = "@slack-kafka-data-highway-alerts"
  escalation_notification_endpoints = "@slack-data-alarm-qa"
  monitor_kafka_topics = [
    "stream.nrGraph.mysql.nr.sound.recording", "stream.nrGraph.mysql.nr.contribution",
    "stream.nrGraph.mysql.nr.contribution.contributed.to.nr.sound.recording", "stream.nrGraph.mysql.nr.contributor",
    "stream.nrGraph.mysql.nr.contributor.is.main.performer.nr.contribution", "stream.nrGraph.mysql.nr.contributor.is.session.musician.nr.contribution",
    "stream.nrGraph.mysql.nr.contributor.is.featuring.performer.nr.contribution",
  ]

  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"
  # Alert on the number of times the metric shows unhealthy tasks within the last hour
  healthy_tasks_critical_number        = 5
}
