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

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/vector/encoder/aws/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.1.0"

  environment = var.environment
}

data "aws_subnets" "private" {
  filter {
    name   = "vpc-id"
    values = [module.vpc_info.vpc_id]
  }
  filter {
    name = "tag:Name"
    values = [
      "prod_vector_subnet_*",
    ]
  }
}

data "aws_iam_policy" "kms_policy" {
  name = "KMS-${var.environment}-${var.service_name}-policy"
}

# RO access to mezz bucket
data "aws_iam_policy" "s3_mezzanine_assets_dir_readonly_policy" {
  name = "S3-${var.s3_mezz_bucket}-RO"
}

# RO access to video mezz bucket
data "aws_iam_policy" "s3_video_mezzanine_assets_readonly_policy" {
  name = "S3-${var.s3_video_bucket}-mezzanine-RO"
}

# Monitors
module "datadog_monitors" {
  for_each = {
    for group in var.healthy_task_monitors : "${group.encoder_type}_${group.physical_location}" => group
  }

  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.13.6"

  environment        = var.environment
  application_family = var.application_family
  service_name       = "${var.service_name}-${each.value.encoder_type}-phys-loc-${each.value.physical_location}*"

  healthy_tasks_monitor_enabled   = true
  healthy_tasks_ok_number         = 1
  healthy_tasks_evaluation_window = "last_1h"

  healthy_tasks_critical_number = 0.1
  healthy_tasks_warning_number  = 0.2

  service_5xx_monitor_enabled = false
  service_cpu_monitor_enabled = false

  screen_dashboard_enabled     = false
  timeseries_dashboard_enabled = false

  notification_endpoints            = each.value.notification
  escalation_notification_endpoints = each.value.escalation
}

resource "datadog_monitor" "events_monitor" {
  for_each = {
    for monitor in local.silent_event_monitors : "${monitor.event}-${monitor.type}" => monitor
  }

  name               = "${var.environment}-${var.service_name}-${each.value.event}-${each.value.type}-silent"
  type               = "query alert"
  message            = "${each.value.event}-${each.value.type} events are not happening Notify: ${each.value.notification}"
  escalation_message = "Escalation to ${each.value.escalation}"
  query              = "sum(last_5m):sum:${each.value.event}{env:${var.environment},encoder:${each.value.encoder_id}} <= 0"

  monitor_thresholds {
    critical = 0
  }

  include_tags      = false
  notify_no_data    = true
  no_data_timeframe = 60
  notify_audit      = false
  renotify_interval = 30
  priority          = 3

  tags = [
    "environment:${var.environment}",
    "service_name:${var.service_name}",
    "application_family:${var.application_family}"
  ]
}

resource "datadog_monitor" "vector_encoding_anomaly_detection_alert" {
  include_tags        = false
  on_missing_data     = "resolve"
  require_full_window = false
  monitor_thresholds {
    critical          = 1
    critical_recovery = 0
    warning           = 0.8
  }
  monitor_threshold_windows {
    recovery_window = "last_15m"
    trigger_window  = "last_15m"
  }
  name    = "Vector Encoding Anomaly Detection Alert"
  type    = "query alert"
  tags    = ["application_family:vector", "env:prod", "team:content-delivery-asset-management"]
  query   = <<EOT
avg(last_15m):anomalies(max:encoding.job_failure{*}.as_count() / max:encoding.job_attempt{*}.as_count() * 100, 'robust', 4, direction='above', interval=60, alert_window='last_15m', count_default_zero='true', seasonality='weekly') >= 1
EOT
  message = <<EOT
Anomaly detected in encoding jobs
EOT
}

# Video Encoding Worker
module "video_encoding_worker_sentry_project" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }

  source             = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"
  service_name       = "${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}"
  environment        = var.environment
  teams              = [var.environment]
  application_family = var.application_family
  platform           = "php"
}

module "vector_encoder_video_ecs_service" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.7.0"
  providers = {
    aws.dns = aws
  }
  environment                         = var.environment
  service_name                        = "${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}"
  non_ecr_image                       = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/vector-worker:latest"
  vpc_id                              = module.vpc_info.vpc_id
  application_family                  = var.application_family
  aws_region                          = var.aws_region
  commit_sha                          = "latest"
  task_type                           = "worker"
  ecs_network_mode                    = "awsvpc"
  ecs_requires_compatibilities        = ["FARGATE"]
  ecs_launch_type                     = "FARGATE"
  ordered_placement_strategy_type     = "random"
  health_check_command                = "php --version"
  health_check_interval               = 300
  health_check_timeout                = 60
  desired_task_count                  = each.value.min_task_count # Set during service creation here and controlled henceforth by autoscaling
  task_cpu                            = 256
  task_memory                         = 1024
  minimum_capacity                    = each.value.min_task_count
  maximum_capacity                    = each.value.max_task_count
  deployment_maximum_percent          = 120 # (deployment_maximum_percent * min_task_count) needs to be >=1
  task_protection_policy_enabled      = true
  splitio_enabled                     = true
  ows_machine_to_machine_enabled      = false
  autoscaling_cpu_policy_enabled      = false
  autoscaling_memory_policy_enabled   = false
  external_autoscaling_policy_enabled = true
  stopped_task_monitoring_enabled     = true
  fargate_service_subnets             = data.aws_subnets.private.ids
  additional_tags                     = var.additional_tags
  availability_zone_rebalancing       = "DISABLED"
  secrets_manager_service_name        = var.service_name

  iam_managed_policy_attachments = [
    data.aws_iam_policy.kms_policy.arn,
    aws_iam_policy.vector_encoder_m2m_token_secrets_manager_policy.arn,
  ]
  environment_variables = [
    {
      Environment = var.environment
    },
    {
      PHP_ENTRYPOINT = "encode_tracks.php"
    },
    {
      USER_AGENT = "${var.environment}-${var.service_name}-video"
    },
    {
      ALLOWED_ENCODER_IDS = var.video_encoder_id
    },
    {
      WGET_IP = "webservices.theorchard.com"
    },
    {
      API_GATEWAY = var.extended_ddex_api_gateway_url
    },
    {
      OWS_DELIVERY_METADATA = "prod-ows-delivery-metadata.theorchard.io"
    },
    {
      ENCODING_PRIORITIES = each.value.encoding_priority
    },
    {
      LOG_LEVEL = "7"
    },
    {
      PHP_MEMORY_LIMIT = "1900M"
    },
    {
      PHYSICAL_LOCATION_ID = each.value.physical_location
    },
    {
      SCRIPT_COUNT = "10"
    },
    {
      LOG_TO_FILE = "0"
    },
    {
      PRODUCT_STORE_MAPPING_URL = "https://ows-product-store-mapping.theorchard.io"
    },
    {
      CURL_FORBID_REUSE = "true"
    },
    {
      SENTRY_DSN = module.video_encoding_worker_sentry_project[each.key].sentry_key_dsn_public_output
    },
    {
      SERVICE_NAME = var.service_name
    },
    {
      DD_DB_HOST = "dd-db.theorchard.com"
    },
    {
      DD_DB_RW_USERNAME = "vector_rw"
    },
    {
      DD_DB_RO_USERNAME = "vector_ro"
    },
    {
      DD_DB_EO_USERNAME = "vector_execonly"
    },
    {
      AR_DB_HOST = "prod-art-relations.cluster-ro-cb22xqmk0y0q.us-east-1.rds.amazonaws.com"
    },
    {
      AR_DB_USERNAME = "dd_user"
    },
    {
      S3_XML_BACKUP_BUCKET = "prod-vector-audit"
    },
    {
      S3_XML_BACKUP_PATH = "/metadata"
    },
    {
      CACHE_HOST = "prod-vector-phys-loc-13.oudhyr.ng.0001.use1.cache.amazonaws.com"
    },
    {
      ENCODING_QUEUE_NAME_PATTERN = "prod-encoding{encoder-id}_e{priority(7)}_d{dms-priority(7)}"
    },
    {
      DELIVERY_QUEUE_NAME_PATTERN = "prod-delivery{encoder-id}_e{priority(7)}_d{dms-priority(7)}"
    },
    {
      APP_LOG_LEVEL = var.app_log_level
    },
  ]

  secrets = [
    {
      AR_DB_PASSWORD = "${var.environment}/${var.service_name}/AR_DB_PASSWORD"
    },
    {
      DD_DB_RO_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_RO_PASSWORD"
    },
    {
      DD_DB_RW_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_RW_PASSWORD"
    },
    {
      DD_DB_EO_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_EO_PASSWORD"
    },
    {
      AWS_KEY_ID = "${var.environment}/${var.service_name}/AWS_KEY_ID"
    },
    {
      AWS_SECRET_KEY = "${var.environment}/${var.service_name}/AWS_SECRET_KEY"
    },
    {
      DATADOG_API_KEY = "${var.environment}/${var.service_name}/DATADOG_API_KEY"
    },
  ]
}

# Audio Encoding Worker
module "audio_encoding_worker_sentry_project" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }

  source             = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"
  service_name       = "${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}"
  environment        = var.environment
  teams              = [var.environment]
  application_family = var.application_family
  platform           = "php"
}

module "vector_encoder_audio_ecs_service" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.7.0"
  providers = {
    aws.dns = aws
  }
  environment                         = var.environment
  service_name                        = "${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}"
  non_ecr_image                       = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/vector-worker:latest"
  vpc_id                              = module.vpc_info.vpc_id
  application_family                  = var.application_family
  aws_region                          = var.aws_region
  commit_sha                          = "latest"
  task_type                           = "worker"
  ecs_network_mode                    = "awsvpc"
  ecs_requires_compatibilities        = ["FARGATE"]
  ecs_launch_type                     = "FARGATE"
  ordered_placement_strategy_type     = "random"
  health_check_command                = "php --version"
  health_check_interval               = 300
  health_check_timeout                = 60
  desired_task_count                  = each.value.min_task_count # Set during service creation here and controlled henceforth by autoscaling
  task_cpu                            = 256
  task_memory                         = 1024
  minimum_capacity                    = each.value.min_task_count
  maximum_capacity                    = each.value.max_task_count
  deployment_maximum_percent          = 120 # (deployment_maximum_percent * min_task_count) needs to be >=1
  task_protection_policy_enabled      = true
  splitio_enabled                     = true
  ows_machine_to_machine_enabled      = false
  autoscaling_cpu_policy_enabled      = false
  autoscaling_memory_policy_enabled   = false
  external_autoscaling_policy_enabled = true
  stopped_task_monitoring_enabled     = true
  fargate_service_subnets             = data.aws_subnets.private.ids
  additional_tags                     = var.additional_tags
  availability_zone_rebalancing       = "DISABLED"
  secrets_manager_service_name        = var.service_name

  iam_managed_policy_attachments = [
    data.aws_iam_policy.kms_policy.arn,
    aws_iam_policy.vector_encoder_m2m_token_secrets_manager_policy.arn,
  ]
  environment_variables = [
    {
      Environment = var.environment
    },
    {
      PHP_ENTRYPOINT = "encode_tracks.php"
    },
    {
      USER_AGENT = "${var.environment}-${var.service_name}-audio"
    },
    {
      ALLOWED_ENCODER_IDS = var.audio_encoder_id
    },
    {
      WGET_IP = "webservices.theorchard.com"
    },
    {
      API_GATEWAY = var.extended_ddex_api_gateway_url
    },
    {
      OWS_DELIVERY_METADATA = "prod-ows-delivery-metadata.theorchard.io"
    },
    {
      ENCODING_PRIORITIES = each.value.encoding_priority
    },
    {
      LOG_LEVEL = "7"
    },
    {
      PHP_MEMORY_LIMIT = "1900M"
    },
    {
      PHYSICAL_LOCATION_ID = each.value.physical_location
    },
    {
      SCRIPT_COUNT = "50"
    },
    {
      STDOUT = "0"
    },
    {
      LOG_TO_FILE = "0"
    },
    {
      transporter_log_location = "\\10.10.40.162\\extremelog\\" # May not need this?
    },
    {
      PRODUCT_STORE_MAPPING_URL = "https://ows-product-store-mapping.theorchard.io"
    },
    {
      CURL_FORBID_REUSE = "true"
    },
    {
      SENTRY_DSN = module.audio_encoding_worker_sentry_project[each.key].sentry_key_dsn_public_output
    },
    {
      SERVICE_NAME = var.service_name
    },
    {
      DD_DB_HOST = "dd-db.theorchard.com"
    },
    {
      DD_DB_RW_USERNAME = "vector_rw"
    },
    {
      DD_DB_RO_USERNAME = "vector_ro"
    },
    {
      DD_DB_EO_USERNAME = "vector_execonly"
    },
    {
      AR_DB_HOST = "prod-art-relations.cluster-ro-cb22xqmk0y0q.us-east-1.rds.amazonaws.com"
    },
    {
      AR_DB_USERNAME = "dd_user"
    },
    {
      S3_XML_BACKUP_BUCKET = "prod-vector-audit"
    },
    {
      S3_XML_BACKUP_PATH = "/metadata"
    },
    {
      CACHE_HOST = "prod-vector-phys-loc-13.oudhyr.ng.0001.use1.cache.amazonaws.com"
    },
    {
      ENCODING_QUEUE_NAME_PATTERN = "prod-encoding{encoder-id}_e{priority(7)}_d{dms-priority(7)}"
    },
    {
      DELIVERY_QUEUE_NAME_PATTERN = "prod-delivery{encoder-id}_e{priority(7)}_d{dms-priority(7)}"
    },
    {
      APP_LOG_LEVEL = var.app_log_level
    },
  ]

  secrets = [
    {
      AR_DB_PASSWORD = "${var.environment}/${var.service_name}/AR_DB_PASSWORD"
    },
    {
      DD_DB_RO_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_RO_PASSWORD"
    },
    {
      DD_DB_RW_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_RW_PASSWORD"
    },
    {
      DD_DB_EO_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_EO_PASSWORD"
    },
    {
      AWS_KEY_ID = "${var.environment}/${var.service_name}/AWS_KEY_ID"
    },
    {
      AWS_SECRET_KEY = "${var.environment}/${var.service_name}/AWS_SECRET_KEY"
    },
    {
      DATADOG_API_KEY = "${var.environment}/${var.service_name}/DATADOG_API_KEY"
    },
  ]
}

# Physical Encoding Worker
module "physical_encoding_worker_sentry_project" {
  for_each = {
    for service in local.flattened_physical_service_list : "physical_location_${service.physical_location}" => service
  }

  source             = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"
  service_name       = "${var.service_name}-physical-phys-loc-${each.value.physical_location}"
  environment        = var.environment
  teams              = [var.environment]
  application_family = var.application_family
  platform           = "php"
}

module "vector_encoder_physical_ecs_service" {
  for_each = {
    for service in local.flattened_physical_service_list : "physical_location_${service.physical_location}" => service
  }
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=5.7.0"
  providers = {
    aws.dns = aws
  }
  environment                         = var.environment
  service_name                        = "${var.service_name}-physical-phys-loc-${each.value.physical_location}"
  non_ecr_image                       = "086679231553.dkr.ecr.${var.aws_region}.amazonaws.com/vector-worker:latest"
  vpc_id                              = module.vpc_info.vpc_id
  application_family                  = var.application_family
  aws_region                          = var.aws_region
  commit_sha                          = "latest"
  task_type                           = "worker"
  ecs_network_mode                    = "awsvpc"
  ecs_requires_compatibilities        = ["FARGATE"]
  ecs_launch_type                     = "FARGATE"
  health_check_command                = "php --version"
  health_check_interval               = 300
  health_check_timeout                = 60
  desired_task_count                  = each.value.min_task_count
  task_cpu                            = 256
  task_memory                         = 1024
  minimum_capacity                    = each.value.min_task_count
  maximum_capacity                    = each.value.max_task_count
  deployment_maximum_percent          = 120 # (deployment_maximum_percent * min_task_count) needs to be >=1
  task_protection_policy_enabled      = true
  splitio_enabled                     = true
  ows_machine_to_machine_enabled      = false
  external_autoscaling_policy_enabled = false
  stopped_task_monitoring_enabled     = true
  fargate_service_subnets             = data.aws_subnets.private.ids
  additional_tags                     = var.additional_tags
  availability_zone_rebalancing       = "DISABLED"
  secrets_manager_service_name        = var.service_name

  iam_managed_policy_attachments = [
    data.aws_iam_policy.kms_policy.arn,
    aws_iam_policy.vector_encoder_m2m_token_secrets_manager_policy.arn,
  ]
  environment_variables = [
    {
      Environment = var.environment
    },
    {
      PHP_ENTRYPOINT = "encode_tracks.php"
    },
    {
      USER_AGENT = "${var.environment}-${var.service_name}-physical"
    },
    {
      ALLOWED_ENCODER_IDS = var.physical_encoder_id
    },
    {
      WGET_IP = "webservices.theorchard.com"
    },
    {
      API_GATEWAY = var.extended_ddex_api_gateway_url
    },
    {
      OWS_DELIVERY_METADATA = "prod-ows-delivery-metadata.theorchard.io"
    },
    {
      ENCODING_PRIORITIES = each.value.encoding_priority
    },
    {
      LOG_LEVEL = "7"
    },
    {
      PHP_MEMORY_LIMIT = "1900M"
    },
    {
      PHYSICAL_LOCATION_ID = each.value.physical_location
    },
    {
      SCRIPT_COUNT = "50"
    },
    {
      LOG_TO_FILE = "0"
    },
    {
      transporter_log_location = "\\10.10.40.162\\extremelog\\" # May not need this?
    },
    {
      PRODUCT_STORE_MAPPING_URL = "https://ows-product-store-mapping.theorchard.io"
    },
    {
      CURL_FORBID_REUSE = "true"
    },
    {
      SENTRY_DSN = module.physical_encoding_worker_sentry_project[each.key].sentry_key_dsn_public_output
    },
    {
      SERVICE_NAME = var.service_name
    },
    {
      DD_DB_HOST = "dd-db.theorchard.com"
    },
    {
      DD_DB_RW_USERNAME = "vector_rw"
    },
    {
      DD_DB_RO_USERNAME = "vector_ro"
    },
    {
      DD_DB_EO_USERNAME = "vector_execonly"
    },
    {
      AR_DB_HOST = "prod-art-relations.cluster-ro-cb22xqmk0y0q.us-east-1.rds.amazonaws.com"
    },
    {
      AR_DB_USERNAME = "dd_user"
    },
    {
      S3_XML_BACKUP_BUCKET = "prod-vector-audit"
    },
    {
      S3_XML_BACKUP_PATH = "/metadata"
    },
    {
      CACHE_HOST = "prod-vector-phys-loc-13.oudhyr.ng.0001.use1.cache.amazonaws.com"
    },
    {
      ENCODING_QUEUE_NAME_PATTERN = "prod-encoding{encoder-id}_e{priority(7)}_d{dms-priority(7)}"
    },
    {
      DELIVERY_QUEUE_NAME_PATTERN = "prod-delivery{encoder-id}_e{priority(7)}_d{dms-priority(7)}"
    },
    {
      APP_LOG_LEVEL = var.app_log_level
    },
  ]

  secrets = [
    {
      AR_DB_PASSWORD = "${var.environment}/${var.service_name}/AR_DB_PASSWORD"
    },
    {
      DD_DB_RO_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_RO_PASSWORD"
    },
    {
      DD_DB_RW_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_RW_PASSWORD"
    },
    {
      DD_DB_EO_PASSWORD = "${var.environment}/${var.service_name}/DD_DB_EO_PASSWORD"
    },
    {
      AWS_KEY_ID = "${var.environment}/${var.service_name}/AWS_KEY_ID"
    },
    {
      AWS_SECRET_KEY = "${var.environment}/${var.service_name}/AWS_SECRET_KEY"
    },
    {
      DATADOG_API_KEY = "${var.environment}/${var.service_name}/DATADOG_API_KEY"
    },
  ]
}

# RW access to encoding buckets
data "aws_iam_policy" "encoding_s3_policy" {
  for_each = {
    for policy in local.s3_policies_to_attach : policy.policy_name => policy
  }
  name = each.value.policy_name
}
