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

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "prod-songwhip-terraform-state"
    key     = "prod/songwhip-presaves/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

locals {
  presaves_dsp_secret_names = flatten([
    for store, clients in var.presave_store_clients : [
      for client in clients : "${upper(replace(store, "-", "_"))}_CLIENT_SECRET/${client}"
    ]
  ])

  presaves_task_queue_env_vars = concat(
    [
      for queue_key in sort(keys(local.presave_store_client_pairs)) :
      {
        "PRESAVES_TASK_QUEUE_URL_${upper(replace(queue_key, "-", "_"))}" = aws_sqs_queue.songwhip_presaves_sqs[queue_key].url
      }
    ],
    [
      for store in sort(local.presave_stores) :
      {
        "PRESAVES_TASK_DLQ_URL_${upper(replace(store, "-", "_"))}" = aws_sqs_queue.songwhip_presaves_dlq[store].url
      }
    ]
  )
}

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

  environment = var.environment
}

module "songwhip_presaves_sentry_project" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"

  environment        = var.environment
  platform           = "javascript"
  service_name       = var.service_name
  application_family = var.application_family
}

module "songwhip_presaves_secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(concat(var.secrets_manager_secret_names, local.presaves_dsp_secret_names))

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

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

  providers = {
    aws.dns = aws
  }

  application_family                       = var.application_family
  environment                              = var.environment
  service_name                             = var.service_name
  aws_region                               = var.region
  commit_sha                               = "latest"
  container_port                           = 8080
  task_type                                = "web_service"
  desired_task_count                       = 2
  minimum_capacity                         = 2
  maximum_capacity                         = 4
  task_cpu                                 = 1024
  task_memory                              = 2048
  load_balancer_idle_timeout               = 300 # 5 min to support execution of large campaigns
  load_balancer_access_logs_s3_bucket_name = "prod-songwhip-lb-logs"
  https_listener_certificate_id            = "14bbece1-4e7f-440f-8fe3-a4f11f50d0fd"
  route53_record_creation_enabled          = false # Disable automatic Route53 record creation since the module prepends "prod-songwhip-" to the record name, which is superfluous.
  custom_waf_arn                           = module.songwhip_presaves_custom_waf.waf_blocking_arn_output
  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
  https_listener_allow_prefix_list_names   = ["vpn-ny-users"]

  iam_managed_policy_attachments = concat(
    # Give Fargate tasks permission to encrypt presave data with KMS
    # Note that we only give encrypt permissions, not decrypt.
    # Only the execution lambdas are allowed to decrypt, and they have a separate policy for that.
    [aws_iam_policy.songwhip_presaves_kms_encrypt_only_policy.arn],
    # Give Fargate tasks permission to send messages and get attributes for all presave SQS queues
    [for p in aws_iam_policy.songwhip_presaves_sqs_send_policy : p.arn],
    # Give Fargate tasks permission to get attributes from all presave SQS deadletter queues
    [for p in aws_iam_policy.songwhip_presaves_sqs_dlq_attributes_policy : p.arn],
    # Give Fargate tasks permission to get attributes from the execution results SQS queue and its deadletter queue
    [aws_iam_policy.songwhip_presaves_execution_results_sqs_attributes_policy.arn],
    # Give Fargate tasks permission to manage SES templates
    [aws_iam_policy.ses_template_management_policy.arn],
  )

  datadog_agent_environment_variables = [
    { JMX_PORT = "9095" },
    { SERVICE_NAME = var.service_name },
    { DD_ENV = var.environment },
    { CONNECTOR_TYPE = "default_sink" },
  ]

  environment_variables = concat(
    [
      { TZ = "UTC" },
      { PORT = "8080" },
      { ENV = var.environment },
      { NODE_ENV = "production" },
      { SONGWHIP_ENV = "production" },
      { TRUSTED_ORIGINS = "https://songwhip.pdesuite.com,https://songwhip.theorchard.com" },
      { DD_TRACE_ENABLED = "true" },
      { DD_LOGS_INJECTION = "true" },
      { AUTH0_M2M_BASE_URL = var.auth0_m2m_base_url },
      { AUTH0_M2M_AUDIENCE = var.auth0_m2m_audience },
      { AUTH0_M2M_CLIENT_ID = var.auth0_m2m_client_id },
      { PRESAVES_KMS_KEY_ID = aws_kms_key.songwhip_presaves_kms_key.key_id },
      { PRESAVES_REDIS_PORT = "6379" },
      { PRESAVES_REDIS_USE_TLS = "true" },
      { PRESAVES_REDIS_HOST = module.songwhip_presaves_redis.redis_primary_endpoint_address },
      { PRESAVES_DB_USER = "songwhip_presaves_app" },
      { PRESAVES_DB_HOST = module.songwhip_presaves_rds.rds_cluster_endpoint },
      { PRESAVES_DB_PORT = module.songwhip_presaves_rds.rds_cluster_port },
      { SENTRY_DSN = module.songwhip_presaves_sentry_project.sentry_key_dsn_public_output },
      { PRESAVES_EXECUTION_RESULTS_QUEUE_URL = module.songwhip_presaves_execution_results_sqs.queue_url },
      { PRESAVES_EXECUTION_RESULTS_DLQ_URL = module.songwhip_presaves_execution_results_sqs.deadletter_queue_url },
    ],
    local.presaves_task_queue_env_vars
  )

  secrets = [
    { PRESAVES_DB_PASSWORD = "${var.environment}/${var.service_name}/PRESAVES_DB_PASSWORD" },
    { WEBHOOK_TOKEN = "${var.environment}/${var.service_name}/WEBHOOK_TOKEN" }
  ]
}

# Create a CNAME record for "presaves.aws-prod.songwhip.com"
# pointing to the Fargate service's load balancer
resource "aws_route53_record" "songwhip_presaves_route53_record" {
  name    = "presaves"
  zone_id = "Z0134392105296KJ8C5A8"
  type    = "CNAME"
  ttl     = 60

  records = [module.songwhip_presaves_fargate_environment.fargate_load_balancer_dns_name]
}

module "songwhip_presaves_custom_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=2.0.2"
  environment       = var.environment
  service_name      = var.service_name
  aws_region        = var.region
  count_waf_enabled = false
  block_waf_enabled = true

  # We exclude the request body size restriction rule because
  # the songwhip-presaves service have bulk endpoints that can receive large payloads.
  # E.g the execution/results endpoint for updating presave execution statuses
  # can be hit with 100 results at a time.
  excluded_rules = [
    "SizeRestrictions_BODY"
  ]
}

module "songwhip_presaves_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.18.1"

  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  application_family                = var.application_family
  teams                             = [var.team_name]
  notification_endpoints            = "@slack-songwhip-alerts"
  escalation_notification_endpoints = "@slack-songwhip-private"
}
