######################################################
## Monitoring and Alerting for File Upload Workflow ##
######################################################

#######################
## Dead Letter Queue ##
#######################

# SQS Dead Letter Queue for failed Step Functions executions
resource "aws_sqs_queue" "file_upload_workflow_dlq" {
  name                       = "${var.environment}-file-upload-workflow-dlq"
  message_retention_seconds  = 1209600  # 14 days
  visibility_timeout_seconds = 300
  # Note: Encryption disabled for LocalStack compatibility
  # In production (QA), sqs_managed_sse_enabled = true

  tags = local.common_tags
}

# SQS Queue Policy to allow EventBridge to send messages
resource "aws_sqs_queue_policy" "file_upload_workflow_dlq_policy" {
  queue_url = aws_sqs_queue.file_upload_workflow_dlq.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Principal = {
          Service = "events.amazonaws.com"
        }
        Action   = "sqs:SendMessage"
        Resource = aws_sqs_queue.file_upload_workflow_dlq.arn
        Condition = {
          ArnEquals = {
            "aws:SourceArn" = aws_cloudwatch_event_rule.file_upload_workflow_failures.arn
          }
        }
      }
    ]
  })
}

##############################
## EventBridge Failure Rule ##
##############################

# EventBridge rule to capture failed Step Functions executions
resource "aws_cloudwatch_event_rule" "file_upload_workflow_failures" {
  name        = "${var.environment}-file-upload-workflow-failures"
  description = "Capture failed Step Functions executions for file upload workflow"

  event_pattern = jsonencode({
    source      = ["aws.states"]
    detail-type = ["Step Functions Execution Status Change"]
    detail = {
      status          = ["FAILED", "TIMED_OUT", "ABORTED"]
      stateMachineArn = [aws_sfn_state_machine.file_upload_workflow.arn]
    }
  })

  tags = local.common_tags
}

# EventBridge target to send failed executions to DLQ
resource "aws_cloudwatch_event_target" "file_upload_workflow_dlq_target" {
  rule      = aws_cloudwatch_event_rule.file_upload_workflow_failures.name
  target_id = "SendToSQSDLQ"
  arn       = aws_sqs_queue.file_upload_workflow_dlq.arn
}

# Note: Datadog monitors are not included for LocalStack
# In production, these monitors alert on:
# - Step Functions execution failures
# - Messages in the DLQ
