# To sink SMF form response from api gateway to snowflake.
module "smf_fanresponse_secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.snoflake_creds_secret_names)

  environment        = var.environment
  application_family = var.application_family
  additional_tags    = var.additional_tags
  service_name       = var.service_name
  secret_name        = each.value
}

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 "snowflake_sink_smf_fanresponse_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=6.5.0"

  providers = {
    aws.dns = aws.networking
  }

  environment        = var.environment
  application_family = var.application_family
  additional_tags    = var.additional_tags

  service_name                         = var.service_name
  non_ecr_image                        = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/${var.ecr_name}:latest"
  aws_region                           = var.aws_region
  desired_task_count                   = 1
  minimum_capacity                     = 1
  maximum_capacity                     = 2
  task_cpu                             = 2048
  task_memory                          = 4096
  container_port                       = 8083
  health_check_grace_period_seconds    = 180
  container_start_period_seconds       = 180
  blocking_waf_enabled                 = true
  health_check_path                    = "/connectors/${var.connector_name}"
  web_service_health_check_command     = "[[ $(curl -s http://localhost:8083/connectors/${var.connector_name}/status | jq -r '.tasks[].state,.connector.state' | sort | uniq) == 'RUNNING' ]] || exit 1"
  vpc_id                               = module.vpc_info.vpc_id
  https_listener_certificate_id        = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  propagate_tags                       = true
  task_placement_failure_alert_enabled = true

  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", # Jumpbox
  ]

  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 = var.service_name
    },
    {
      CONNECTOR_TYPE = "default_sink"
    },
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      CONNECT_GROUP_UNIQUE_IDENTIFIER = "${var.environment}-${var.service_name}"
    },
    {
      CONSUMER_PARTITION_ASSIGNMENT_STRATEGY = "org.apache.kafka.clients.consumer.RoundRobinAssignor"
    },
    {
      MAX_TASKS = 1
    },
    {
      BUFFER_COUNT_RECORDS = 10000
    },
    {
      BUFFER_SIZE_BYTES = 5000000
    },
    {
      BUFFER_FLUSH_TIME = 180 # 3 mins
    },
    {
      CONNECT_BOOTSTRAP_SERVERS = var.connect_bootstrap_servers
    },
    {
      SNOWFLAKE_INGESTION_METHOD = "SNOWPIPE_STREAMING"
    },
    {
      SNOWFLAKE_HOST = "delphi.us-east-1.snowflakecomputing.com:443"
    },
    {
      SNOWFLAKE_USER = "PROD_KAFKA_CONNECT_FORMRESPONSE"
    },
    {
      SNOWFLAKE_ROLE = "FANSIFTER_APP_REPORTING_DB_PROD_CRM_FANS_SCHEMA_READWRITE"
    },
    {
      SNOWFLAKE_DATABASE = "FANSIFTER_APP_REPORTING"
    },
    {
      SNOWFLAKE_SCHEMA = "PROD_CRM_FANS"
    },
    {
      SERVICE_NAME = var.service_name
    },
    {
      KAFKA_TOPICS = join(",", [
        "event.smf.fanresponse",
        "event.tunespeak.fanresponse",
        "event.wyng.fanresponse",
        "event.mtl.fanresponse",
      ])
    },
    {
      SNOWFLAKE_TOPIC_TABLE_MAP = join(",", [
        "event.smf.fanresponse:EVENT_FAN_RESPONSE",
        "event.tunespeak.fanresponse:EVENT_FAN_RESPONSE",
        "event.wyng.fanresponse:EVENT_FAN_RESPONSE",
        "event.mtl.fanresponse:EVENT_FAN_RESPONSE",
      ])
    },
    {
      DLQ_TOPIC_NAME = "dlq.fanresponse"
    },
  ]
}

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


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

  environment        = var.environment
  application_family = var.application_family
  additional_tags    = var.additional_tags
  environment_type   = "fargate"
  service_name       = var.service_name
  connector_type     = "default_sink"

  notification_endpoints            = "@slack-kafka-data-highway-alerts"
  escalation_notification_endpoints = "@slack-data"
  monitor_kafka_topics_cluster_name = "prod-managed-kafka-cdc-destination"
  monitor_kafka_topics              = ["event.smf.fanresponse", "event.tunespeak.fanresponse", "event.wyng.fanresponse", "event.mtl.fanresponse", "dlq.fanresponse"]
  dlq_topic_name                    = "dlq.fanresponse"

  healthy_tasks_monitor_enabled = true
  service_cpu_monitor_enabled   = true
  error_monitor_enabled         = true
}
