locals {
  lambda_name = "${var.service_name}-sqs-processor"
}

# Sentry project for the lambda
module "songwhip_api_sqs_sentry" {
  source = "git@github.com:theorchard/terraform-sentry//?ref=5.0.0"

  environment        = var.environment
  teams              = [var.environment]
  service_name       = local.lambda_name
  application_family = var.application_family
  platform           = "node"
}

# SQS Queue Configuration
module "songwhip_api_sqs" {
  source = "git@github.com:theorchard/terraform-sqs.git?ref=2.4.1"

  environment        = var.environment
  application_family = var.application_family
  queue_name         = var.service_name

  sqs_visibility_timeout_seconds       = 360        # 6 minutes
  sqs_max_message_size                 = 1024 * 100 # 100 KB
  sqs_deadletter_enabled               = true
  deadletter_message_retention_seconds = 1209600    # 14 days
  deadletter_max_receive_count         = 3          # Message will be retried 3 times before moving to DLQ
  deadletter_max_message_size          = 1024 * 100 # 100 KB
}

# IAM Policy for Fargate service to send messages to SQS
data "aws_iam_policy_document" "fargate_sqs_send_policy_document" {
  statement {
    actions = [
      "sqs:SendMessage",
      "sqs:GetQueueUrl",
      "sqs:GetQueueAttributes"
    ]

    resources = [
      module.songwhip_api_sqs.queue_arn
    ]
  }
}

resource "aws_iam_policy" "fargate_sqs_send_policy" {
  name        = "SQS-${var.environment}-${var.service_name}-send-messages"
  description = "Allow Fargate service to send messages to SQS queue"
  policy      = data.aws_iam_policy_document.fargate_sqs_send_policy_document.json
}

# Lambda function to process SQS messages and call the API endpoint
module "sqs_processor_lambda" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=5.3.0"

  environment        = var.environment
  lambda_name        = local.lambda_name
  lambda_description = "Processes SQS messages and calls songwhip-api endpoints"
  application_family = var.application_family

  # VPC configuration to reach Fargate service
  vpc_enabled    = true
  vpc_id         = module.vpc_info.vpc_id
  vpc_subnet_ids = module.vpc_info.default_private_subnet_ids

  # Container image for Lambda
  use_container_image = true

  # SQS event source mapping
  sqs_event_enabled                   = true
  event_source_mapping_queue_name     = module.songwhip_api_sqs.queue_name
  event_source_mapping_batch_size     = 10
  event_source_mapping_batch_window   = 5 # Wait up to 5 seconds to collect batch
  event_source_mapping_response_types = ["ReportBatchItemFailures"]

  # Function configuration
  lambda_function_timeout                        = 300 # 5 minutes
  lambda_function_memory_size                    = 512
  lambda_function_reserved_concurrent_executions = 2

  # Error handling
  dlq_enabled = true
  dlq_type    = "sns"

  # Monitoring
  datadog_enabled = true

  lambda_function_environment_variables = {
    SONGWHIP_API_URL = var.songwhip_api_url
    SENTRY_DSN       = module.songwhip_api_sqs_sentry.sentry_key_dsn_public_output
    ENV              = var.environment
  }
}

# Grant Lambda permission to read from SQS
resource "aws_iam_role_policy_attachment" "lambda_sqs_execution_policy" {
  role       = module.sqs_processor_lambda.lambda_role_id
  policy_arn = module.songwhip_api_sqs.sqs_minimal_policy_arn_output
}

# Datadog monitors
module "sqs_processor_lambda_datadog_monitor" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/lambda?ref=6.15.2"

  service_name = local.lambda_name
  environment  = var.environment

  # The invocation monitor is not needed now in QA, since we have low traffic
  lambda_invocation_monitor_enabled = false

  notification_endpoints            = "@slack-songwhip-alerts-dev"
  escalation_notification_endpoints = "@slack-songwhip-devs"
}
