################################################################
## IAM Roles and Policies for Adjustment File Ingest Workflow ##
################################################################

########################
## Step Functions IAM ##
########################

# IAM role for Step Functions state machine
resource "aws_iam_role" "adjustment_file_ingest_workflow_role" {
  name = "${var.environment}-adjustment-file-ingest-workflow-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Principal = {
          Service = "states.amazonaws.com"
        }
        Action = "sts:AssumeRole"
      }
    ]
  })

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

# IAM policy for Step Functions to invoke lambdas
resource "aws_iam_role_policy" "adjustment_file_ingest_workflow_policy" {
  name = "${var.environment}-adjustment-file-ingest-workflow-policy"
  role = aws_iam_role.adjustment_file_ingest_workflow_role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "lambda:InvokeFunction"
        ]
        Resource = [
          data.aws_lambda_function.adjustment_file_initialize.arn,
          "${data.aws_lambda_function.adjustment_file_initialize.arn}:*"
        ]
      },
      {
        Effect = "Allow"
        Action = [
          "logs:CreateLogDelivery",
          "logs:GetLogDelivery",
          "logs:UpdateLogDelivery",
          "logs:DeleteLogDelivery",
          "logs:ListLogDeliveries",
          "logs:PutResourcePolicy",
          "logs:DescribeResourcePolicies",
          "logs:DescribeLogGroups"
        ]
        Resource = "*"
      },
      {
        Effect = "Allow"
        Action = [
          "xray:PutTraceSegments",
          "xray:PutTelemetryRecords"
        ]
        Resource = "*"
      }
    ]
  })
}

########################
## Lambda Permissions ##
########################

# Allow Step Functions to invoke Adjustment File Initialize Lambda
resource "aws_lambda_permission" "allow_sfn_invoke_adjustment_file_initialize" {
  statement_id  = "AllowExecutionFromStepFunctions"
  action        = "lambda:InvokeFunction"
  function_name = data.aws_lambda_function.adjustment_file_initialize.function_name
  principal     = "states.amazonaws.com"
  source_arn    = aws_sfn_state_machine.adjustment_file_ingest_workflow.arn
}
