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

  application_family = var.application_family
  environment        = var.environment
  platform           = "python"
  service_name       = var.sr_delivery_tiktok_function_name
  teams              = [var.environment]
}

data "aws_iam_policy_document" "s3_sr_versions_lambda_sr_delivery_tiktok_policy_document" {
  statement {
    actions = [
      "s3:GetObject",
      "s3:GetObjectVersion",
      "s3:GetBucketVersioning"
    ]

    resources = [
      "arn:aws:s3:::${var.environment}-${var.sr_versions_bucket}/*"
    ]
  }

  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      "arn:aws:s3:::${var.environment}-${var.sr_versions_bucket}"
    ]
  }
}

data "aws_iam_policy_document" "s3_sr_delivery_audit_lambda_sr_delivery_tiktok_policy_document" {
  statement {
    actions = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:GetObjectVersion"
    ]

    resources = [
      "arn:aws:s3:::${var.environment}-${var.sr_delivery_audit_bucket}/*"
    ]
  }

  statement {
    actions = [
      "s3:ListBucket",
    ]

    resources = [
      "arn:aws:s3:::${var.environment}-${var.sr_delivery_audit_bucket}"
    ]
  }
}

resource "aws_iam_policy" "s3_sr_versions_lambda_sr_delivery_tiktok_policy" {
  name   = "S3-${var.environment}-${var.sr_versions_bucket}-lambda-sr-delivery-tiktok-R-policy"
  policy = data.aws_iam_policy_document.s3_sr_versions_lambda_sr_delivery_tiktok_policy_document.json
}

resource "aws_iam_policy" "s3_sr_delivery_audit_lambda_sr_delivery_tiktok_policy" {
  name   = "S3-${var.environment}-${var.sr_delivery_audit_bucket}-lambda-sr-delivery-tiktok-RW-policy"
  policy = data.aws_iam_policy_document.s3_sr_delivery_audit_lambda_sr_delivery_tiktok_policy_document.json
}

data "aws_iam_policy" "s3_mezz_tiktok_ro_delivery" {
  name = "S3-${var.environment}-orcd-mezzanine-assets-RO"
}

module "lambda_sr_delivery_tiktok" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=4.2.0"

  application_family       = var.application_family
  datadog_advanced_enabled = true
  environment              = var.environment
  lambda_name              = var.sr_delivery_tiktok_function_name
  lambda_description       = "Delivery of sound recording to TikTok"
  lambda_function_timeout  = var.lambda_default_timeout
  use_container_image      = true
  vpc_id                   = var.vpc_id
  vpc_subnet_ids           = var.vpc_subnet_ids

  lambda_function_memory_size = 3000

  iam_managed_policy_attachments = [
    aws_iam_policy.s3_sr_versions_lambda_sr_delivery_tiktok_policy.arn,
    aws_iam_policy.s3_sr_delivery_audit_lambda_sr_delivery_tiktok_policy.arn,
    data.aws_iam_policy.s3_mezz_tiktok_ro_delivery.arn
  ]

  lambda_function_environment_variables = {
    ENVIRONMENT                       = var.environment
    TIKTOK_S3_BUCKET_NAME             = var.tiktok_s3_bucket_name
    TIKTOK_S3_BASE_FOLDERNAME         = var.tiktok_s3_base_foldername
    PERFORM_FINAL_DDEX_COMPARISON     = var.perform_final_ddex_comparison
    LOGGER_LEVEL                      = "WARN"
    DDEX_FILE_VERSION                 = var.ddex_file_version_tiktok
  }

  lambda_function_reserved_concurrent_executions = "160"
}

module "tiktok_fingerprint_delivery_password" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"

  environment                    = var.environment
  service_name                   = var.sr_delivery_tiktok_function_name
  secret_name                    = "TIKTOK_FINGERPRINT_DELIVERY_PASSWORD"
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

module "tiktok_fingerprint_delivery_user_name" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"

  environment                    = var.environment
  service_name                   = var.sr_delivery_tiktok_function_name
  secret_name                    = "TIKTOK_FINGERPRINT_DELIVERY_USER_NAME"
  application_family             = var.application_family
  secret_recovery_window_in_days = 7
}

locals {
  sr_delivery_tiktok_tags = flatten([
    local.env_tags,
    "service:${var.osr_fingerprint_filter_name}",
    "service_name:${var.osr_fingerprint_filter_name}",
    local.team_tags,
  ])
}

resource "datadog_monitor" "sound_recording_tiktok_delivery_daily_limit" {
  name    = "${var.environment}-sound-recording-tiktok-delivery-daily-limit"
  type    = "metric alert"
  message = "{{#is_alert}} Critical: We have delivered over 395k updates to TikTok today. Their limit is 400k. {{/is_alert}} {{#is_warning}} Warning: We have delivered over 350k updates to TikTok today. Their limit is 400k. {{/is_warning}} {{#is_recovery}} Recovery: Number of deliveries to TikTok is back to normal. {{/is_recovery}} Notify: ${var.notification_endpoints}"

  query = "max(last_1h):max:snowflake.custom.query_monitor.sound_recording_tiktok_delivery_daily_limit{*} >= 395000"

  monitor_thresholds {
    warning  = 350000
    critical = 395000
  }

  notify_no_data      = true
  no_data_timeframe   = 240
  notify_audit        = false
  renotify_interval   = 30
  timeout_h           = 0
  require_full_window = false

  tags = local.sr_delivery_tiktok_tags
}

resource "datadog_monitor" "sound_recording_tiktok_no_success_deliveries" {
  name    = "${var.environment}-sound-recording-tiktok-no-success-deliveries"
  type    = "metric alert"
  message = "{{#is_alert}} Critical: We have made 0 successful deliveries to TikTok in the past 3 hours. More info at https://www.notion.so/Outages-Error-Alerts-Runbook-1e797177520f80b798a9c3f5f51bff6a {{/is_alert}} {{#is_warning}} Warning: The number of deliveries to TikTok has been very low in the past 3 hours. {{/is_warning}} {{#is_recovery}} Recovery: Number of deliveries to TikTok is back to normal. {{/is_recovery}} Notify: ${var.notification_endpoints}"

  query = "max(last_1h):max:snowflake.custom.query_monitor.sound_recording_tiktok_no_success_deliveries{*} <= 0"

  monitor_thresholds {
    warning  = 5
    critical = 0
  }

  notify_no_data      = true
  no_data_timeframe   = 240
  notify_audit        = false
  renotify_interval   = 30
  timeout_h           = 0
  require_full_window = false

  tags = local.tags
}

module "datadog_lambda_sr_delivery_tiktok_dashboards" {
  source                            = "git@github.com:theorchard/terraform-datadog.git//modules/lambda?ref=6.13.6"
  service_name                      = var.sr_delivery_tiktok_function_name
  environment                       = var.environment
  lambda_invocation_monitor_enabled = false
  lambda_error_monitor_enabled      = true
  notification_endpoints            = var.notification_endpoints
}
