#####################################
## adjustment-file-ingest-workflow ##
#####################################

# Data sources for existing lambda functions
data "aws_lambda_function" "adjustment_file_initialize" {
  function_name = "${var.environment}-lambda-abacus-adjustment-file-initialize"
}

# CloudWatch Log Group for Step Functions
resource "aws_cloudwatch_log_group" "adjustment_file_ingest_workflow_logs" {
  name              = "/aws/vendedlogs/states/${var.environment}-adjustment-file-ingest-workflow"
  retention_in_days = 365 # 1 year retention required

  tags = {
    application_family = var.application_family
    environment        = var.environment
    service_name       = var.service_name
    terraformed        = true
  }
}

# Step Functions state machine
resource "aws_sfn_state_machine" "adjustment_file_ingest_workflow" {
  name     = "${var.environment}-adjustment-file-ingest-workflow"
  role_arn = aws_iam_role.adjustment_file_ingest_workflow_role.arn

  definition = jsonencode({
    Comment        = "Adjustment file ingestion workflow with initialization"
    TimeoutSeconds = 1200 # 20 minutes overall timeout for entire workflow
    StartAt        = "InitializeBatch"
    States = {
      InitializeBatch = {
        Type           = "Task"
        Resource       = data.aws_lambda_function.adjustment_file_initialize.arn
        TimeoutSeconds = 30 # 30 seconds for batch initialization
        ResultPath     = "$.lambdaResult"
        Retry = [
          {
            ErrorEquals = [
              "Lambda.ServiceException",
              "Lambda.TooManyRequestsException",
              "Lambda.SdkClientException",
              "TransientError"
            ]
            IntervalSeconds = 2
            MaxAttempts     = 3
            BackoffRate     = 2.0
          },
          {
            ErrorEquals     = ["States.TaskFailed", "States.Timeout"]
            IntervalSeconds = 1
            MaxAttempts     = 2
            BackoffRate     = 1.5
          }
        ]
        Catch = [
          {
            ErrorEquals = ["States.ALL"]
            ResultPath  = "$.error"
            Next        = "InitializeFailed"
          }
        ]
        End = true
      }
      InitializeFailed = {
        Type  = "Fail"
        Cause = "Batch initialization failed after retries"
        Error = "InitializeBatchError"
      }
    }
  })

  logging_configuration {
    log_destination        = "${aws_cloudwatch_log_group.adjustment_file_ingest_workflow_logs.arn}:*"
    include_execution_data = true
    level                  = "ALL"
  }

  tracing_configuration {
    enabled = true
  }

  tags = {
    application_family = var.application_family
    environment        = var.environment
    service_name       = var.service_name
    terraformed        = true
  }
}
