####################################
## adjustment-file-apply-workflow ##
####################################

data "aws_lambda_function" "adjustment_file_apply" {
  function_name = "${var.environment}-lambda-abacus-adjustments-apply"
}

resource "aws_cloudwatch_log_group" "adjustment_file_apply_workflow_logs" {
  name              = "/aws/vendedlogs/states/${var.environment}-adjustment-file-apply-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
  }
}

resource "aws_sfn_state_machine" "adjustment_file_apply_workflow" {
  name     = "${var.environment}-adjustment-file-apply-workflow"
  role_arn = aws_iam_role.adjustment_file_apply_workflow_role.arn

  definition = jsonencode({
    Comment        = "Adjustment file apply workflow"
    TimeoutSeconds = 1200 # 20 minutes overall timeout for entire workflow
    StartAt        = "ApplyAdjustments"
    States = {
      ApplyAdjustments = {
        Type           = "Task"
        Resource       = data.aws_lambda_function.adjustment_file_apply.arn
        TimeoutSeconds = 900 # 15 minutes for apply
        Parameters = {
          "target_id.$"       = "$.detail.metadata.target_id"
          "abacus_event_id.$" = "$.detail.data.abacus_event_id"
        }
        # Auto-retry disabled (MaxAttempts = 0); retry is user-triggered. Tiers
        # kept as a template only; do not raise MaxAttempts here.
        Retry = [
          {
            ErrorEquals = [
              "Lambda.ServiceException",
              "Lambda.TooManyRequestsException",
              "Lambda.SdkClientException"
            ]
            IntervalSeconds = 2
            MaxAttempts     = 0
            BackoffRate     = 2.0
          },
          {
            ErrorEquals     = ["States.TaskFailed", "States.Timeout"]
            IntervalSeconds = 1
            MaxAttempts     = 0
            BackoffRate     = 1.5
          }
        ]
        Catch = [
          {
            ErrorEquals = ["States.ALL"]
            ResultPath  = "$.error"
            Next        = "ApplyFailed"
          }
        ]
        End = true
      }
      ApplyFailed = {
        Type  = "Fail"
        Cause = "Adjustment apply failed"
        Error = "ApplyError"
      }
    }
  })

  logging_configuration {
    log_destination        = "${aws_cloudwatch_log_group.adjustment_file_apply_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
  }
}
