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
  }
}

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     = "prod/vector/delivery/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_acm_certificate" "theorchard_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

data "aws_subnets" "private" {
  filter {
    name   = "vpc-id"
    values = [module.vpc_info.vpc_id]
  }
  filter {
    name = "tag:Name"
    # Don't use prod_private_subnet_0 and prod_private_subnet_1 because they are low on available IPs and this service runs a LOT of tasks
    values = [
      "prod_vector_subnet_*",
    ]
  }
}

# Create separate EFS file systems for each audio worker priority.
module "delivery_worker_audio_efs" {
  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-efs.git//?ref=4.1.0"

  providers = {
    aws.dns = aws.networking
  }

  environment         = var.environment
  service_name        = "${var.service_name}-audio-p${each.value.encoding_priority}"
  application_family  = var.application_family
  vpc_id              = module.vpc_info.vpc_id
  subnet_ids          = data.aws_subnets.private.ids
  owner_gid           = "1010"
  owner_uid           = "1010"
  efs_throughput_mode = "elastic"
  backup_enabled      = false

  efs_ingress_additional_cidr_blocks = [
    "162.49.75.0/24", # Allow access from SME VPN
  ]
}

# Create separate EFS file systems for each video worker priority.
module "delivery_worker_video_efs" {
  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-efs.git//?ref=4.1.0"

  providers = {
    aws.dns = aws.networking
  }

  environment         = var.environment
  service_name        = "${var.service_name}-video-p${each.value.encoding_priority}"
  application_family  = var.application_family
  vpc_id              = module.vpc_info.vpc_id
  subnet_ids          = data.aws_subnets.private.ids
  owner_gid           = "1010"
  owner_uid           = "1010"
  efs_throughput_mode = "elastic"
  backup_enabled      = false

  efs_ingress_additional_cidr_blocks = [
    "162.49.75.0/24", # Allow access from SME VPN
  ]
}

# Worker task count monitors
module "datadog_monitors" {
  for_each = {
    for group in var.healthy_task_monitors : "${group.worker_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.worker_type}-phys-loc-${each.value.physical_location}*"

  healthy_tasks_monitor_enabled   = true
  healthy_tasks_ok_number         = 1
  healthy_tasks_evaluation_window = each.value.healthy_tasks_evaluation_window

  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
}

# S3 vector-audit RW access
data "aws_iam_policy" "s3_vector_audit_bucket_policy" {
  name = "S3-${var.environment}-vector-audit-RW"
}

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"
}

# RO 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
}

# Audio Delivery Worker
module "audio_delivery_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"
}

data "aws_iam_policy_document" "audio_delivery_worker_sentry_project_secrets_manager_policy_document" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  statement {
    actions = [
      "secretsmanager:GetResourcePolicy",
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
      "secretsmanager:ListSecretVersionIds",
    ]

    resources = [
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}/",
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}/*",
    ]
  }

  statement {
    actions = [
      "secretsmanager:GetRandomPassword",
    ]

    resources = [
      "*",
    ]
  }
}

resource "aws_iam_policy" "audio_delivery_worker_sentry_project_secrets_manager_policy" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  name   = "Secretsmanager-${var.service_name}-audio-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-policy"
  policy = data.aws_iam_policy_document.audio_delivery_worker_sentry_project_secrets_manager_policy_document[each.key].json
  tags   = local.tags
}

locals {
  # Audio delivery uses the Fargate default 20 GiB ephemeral disk, set explicitly here so the EFS
  # threshold derives from it (20 renders no ephemeral_storage block — behaviour-neutral). Threshold
  # = disk − 8 GiB reserve (~4 GiB measured overhead + ~4 GiB scratch; smaller than video's 10 because
  # audio packages are tiny). Bigger packages stage on EFS, not the local dir.
  audio_delivery_ephemeral_gib     = 20
  audio_delivery_efs_threshold_gib = local.audio_delivery_ephemeral_gib - 8
}

module "vector_delivery_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=6.1.1"
  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
  secrets_manager_service_name        = var.service_name
  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
  task_ephemeral_storage_size         = local.audio_delivery_ephemeral_gib
  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"

  # IAM policies used by the task role to pull configs from s3
  iam_managed_policy_attachments = [
    data.aws_iam_policy.kms_policy.arn,
    aws_iam_policy.secrets_manager_delivery_spec_policy.arn,
    module.delivery_worker_audio_efs[each.key].efs_iam_policy_arn_output,
  ]

  docker_volumes = [
    {
      name            = "${var.environment}-${var.service_name}-audio-p${each.value.encoding_priority}"
      file_system_id  = module.delivery_worker_audio_efs[each.key].efs_file_system_id_output
      access_point_id = module.delivery_worker_audio_efs[each.key].efs_access_point_id_output
    }
  ]

  docker_volume_mount_points = [
    {
      source_volume  = "${var.environment}-${var.service_name}-audio-p${each.value.encoding_priority}"
      container_path = var.efs_mount_path
    }
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      PHP_ENTRYPOINT = "deliver_tracks.php"
    },
    {
      ALLOWED_ENCODER_IDS = var.audio_encoder_id
    },
    {
      WGET_IP = "webservices.theorchard.com"
    },
    {
      API_GATEWAY = "83js3jafrc-vpce-04f8c4be29fb2bd59.execute-api.us-east-1.amazonaws.com"
    },
    {
      ENCODING_PRIORITIES = each.value.encoding_priority
    },
    {
      LOG_LEVEL = "7"
    },
    {
      PHP_MEMORY_LIMIT = "1900M"
    },
    {
      PHYSICAL_LOCATION_ID = each.value.physical_location
    },
    {
      SCRIPT_COUNT = "50"
    },
    {
      transporter_log_location = "itmsextremelogs"
    },
    {
      PRODUCT_STORE_MAPPING_URL = "https://ows-product-store-mapping.theorchard.io"
    },
    {
      WORKER_TIMEOUT = "24h"
    },
    {
      SENTRY_DSN = module.audio_delivery_worker_sentry_project[each.key].sentry_key_dsn_public_output
    },
    {
      SERVICE_NAME = var.service_name
    },
    {
      USE_EFS_FOR_PACKAGES_LARGER_THAN_GIB = tostring(local.audio_delivery_efs_threshold_gib)
    },
    {
      EFS_PATH = var.efs_mount_path
    },
    {
      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"
    },
  ]
}

# This rule allows audio delivery fargate tasks to access the EFS mount
resource "aws_security_group_rule" "vector_delivery_audio_allow_efs_sg_inbound" {
  for_each = {
    for service in local.flattened_audio_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }

  from_port                = 2049
  protocol                 = "tcp"
  security_group_id        = module.delivery_worker_audio_efs[each.key].efs_security_group_id_output
  source_security_group_id = module.vector_delivery_audio_ecs_service[each.key].fargate_security_group_id
  to_port                  = 2049
  type                     = "ingress"
}

locals {
  # Video delivery stages each package on the local ephemeral disk unless it is larger than this
  # threshold, in which case it stages on EFS. Derived from the disk size minus a fixed ~10 GiB
  # reserved for overhead that does not scale with the disk: ~1 GiB Fargate platform + ~4 GiB
  # idle baseline (≈3 GiB decompressed container images + ~1 GiB OS/agents) + ~0.15 GiB measured
  # delivery scratch + safety headroom.
  video_delivery_ephemeral_gib     = 98
  video_delivery_efs_threshold_gib = local.video_delivery_ephemeral_gib - 10
}

# Video Delivery Worker
module "video_delivery_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"
}

data "aws_iam_policy_document" "video_delivery_worker_sentry_project_secrets_manager_policy_document" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  statement {
    actions = [
      "secretsmanager:GetResourcePolicy",
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
      "secretsmanager:ListSecretVersionIds",
    ]

    resources = [
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}/",
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}/*",
    ]
  }

  statement {
    actions = [
      "secretsmanager:GetRandomPassword",
    ]

    resources = [
      "*",
    ]
  }
}

resource "aws_iam_policy" "video_delivery_worker_sentry_project_secrets_manager_policy" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }
  name   = "Secretsmanager-${var.service_name}-video-phys-loc-${each.value.physical_location}-p${each.value.encoding_priority}-policy"
  policy = data.aws_iam_policy_document.video_delivery_worker_sentry_project_secrets_manager_policy_document[each.key].json
  tags   = local.tags
}

module "vector_delivery_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=6.1.1"
  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
  secrets_manager_service_name        = var.service_name
  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"
  task_ephemeral_storage_size         = local.video_delivery_ephemeral_gib
  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                         = 2048
  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"

  # IAM policies used by the task role to pull configs from s3
  iam_managed_policy_attachments = [
    data.aws_iam_policy.kms_policy.arn,
    aws_iam_policy.secrets_manager_delivery_spec_policy.arn,
    module.delivery_worker_video_efs[each.key].efs_iam_policy_arn_output,
  ]

  docker_volumes = [
    {
      name            = "${var.environment}-${var.service_name}-video-p${each.value.encoding_priority}"
      file_system_id  = module.delivery_worker_video_efs[each.key].efs_file_system_id_output
      access_point_id = module.delivery_worker_video_efs[each.key].efs_access_point_id_output
    }
  ]

  docker_volume_mount_points = [
    {
      source_volume  = "${var.environment}-${var.service_name}-video-p${each.value.encoding_priority}"
      container_path = var.efs_mount_path
    }
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      PHP_ENTRYPOINT = "deliver_tracks.php"
    },
    {
      ALLOWED_ENCODER_IDS = var.video_encoder_id
    },
    {
      WGET_IP = "webservices.theorchard.com"
    },
    {
      API_GATEWAY = "83js3jafrc-vpce-04f8c4be29fb2bd59.execute-api.us-east-1.amazonaws.com"
    },
    {
      ENCODING_PRIORITIES = each.value.encoding_priority
    },
    {
      LOG_LEVEL = "7"
    },
    {
      PHP_MEMORY_LIMIT = "1900M"
    },
    {
      PHYSICAL_LOCATION_ID = each.value.physical_location
    },
    {
      SCRIPT_COUNT = "20"
    },
    {
      transporter_log_location = "itmsextremelogs"
    },
    {
      PRODUCT_STORE_MAPPING_URL = "https://ows-product-store-mapping.theorchard.io"
    },
    {
      WORKER_TIMEOUT = "24h"
    },
    {
      SENTRY_DSN = module.video_delivery_worker_sentry_project[each.key].sentry_key_dsn_public_output
    },
    {
      SERVICE_NAME = var.service_name
    },
    {
      USE_EFS_FOR_PACKAGES_LARGER_THAN_GIB = tostring(local.video_delivery_efs_threshold_gib)
    },
    {
      EFS_PATH = var.efs_mount_path
    },
    {
      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"
    },
  ]
}

# This rule allows video delivery fargate tasks to access the EFS mount
resource "aws_security_group_rule" "vector_delivery_video_allow_efs_sg_inbound" {
  for_each = {
    for service in local.flattened_video_service_list : "physical_location_${service.physical_location}-encoding_priority_${service.encoding_priority}" => service
  }

  from_port                = 2049
  protocol                 = "tcp"
  security_group_id        = module.delivery_worker_video_efs[each.key].efs_security_group_id_output
  source_security_group_id = module.vector_delivery_video_ecs_service[each.key].fargate_security_group_id
  to_port                  = 2049
  type                     = "ingress"
}

# Physical Delivery Worker
module "physical_delivery_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"
}

data "aws_iam_policy_document" "physical_delivery_worker_sentry_project_secrets_manager_policy_document" {
  for_each = {
    for service in local.flattened_physical_service_list : "physical_location_${service.physical_location}" => service
  }
  statement {
    actions = [
      "secretsmanager:GetResourcePolicy",
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret",
      "secretsmanager:ListSecretVersionIds",
    ]

    resources = [
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}-physical-phys-loc-${each.value.physical_location}/",
      "arn:aws:secretsmanager:*:*:secret:${var.environment}/${var.service_name}-physical-phys-loc-${each.value.physical_location}/*",
    ]
  }

  statement {
    actions = [
      "secretsmanager:GetRandomPassword",
    ]

    resources = [
      "*",
    ]
  }
}

resource "aws_iam_policy" "physical_delivery_worker_sentry_project_secrets_manager_policy" {
  for_each = {
    for service in local.flattened_physical_service_list : "physical_location_${service.physical_location}" => service
  }
  name   = "Secretsmanager-${var.service_name}-physical-phys-loc-${each.value.physical_location}-policy"
  policy = data.aws_iam_policy_document.physical_delivery_worker_sentry_project_secrets_manager_policy_document[each.key].json
  tags   = local.tags
}

module "vector_delivery_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=6.1.1"
  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
  secrets_manager_service_name        = var.service_name
  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 # 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"

  # IAM policies used by the task role to pull configs from s3
  iam_managed_policy_attachments = [
    data.aws_iam_policy.kms_policy.arn,
    aws_iam_policy.secrets_manager_delivery_spec_policy.arn,
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      PHP_ENTRYPOINT = "deliver_tracks.php"
    },
    {
      ALLOWED_ENCODER_IDS = var.physical_encoder_id
    },
    {
      WGET_IP = "webservices.theorchard.com"
    },
    {
      API_GATEWAY = "83js3jafrc-vpce-04f8c4be29fb2bd59.execute-api.us-east-1.amazonaws.com"
    },
    {
      ENCODING_PRIORITIES = each.value.encoding_priority
    },
    {
      LOG_LEVEL = "7"
    },
    {
      PHP_MEMORY_LIMIT = "900M"
    },
    {
      PHYSICAL_LOCATION_ID = each.value.physical_location
    },
    {
      SCRIPT_COUNT = "20"
    },
    {
      STORED_PHYSICAL_FORMATS = "mpg,3gp,stored_mov,mp4,wmv,ts,mxf"
    },
    {
      no_physical_encoding = "1"
    },
    {
      transporter_log_location = "itmsextremelogs"
    },
    {
      PRODUCT_STORE_MAPPING_URL = "https://ows-product-store-mapping.theorchard.io"
    },
    {
      WORKER_TIMEOUT = "12h"
    },
    {
      SENTRY_DSN = module.physical_delivery_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"
    },
  ]
}
