resource "aws_iam_role" "ds_moments_step_functions_triggering_role" {
  name = "${var.environment}-${var.service_name}-trigger-state-machine"

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

data "aws_iam_policy_document" "step_functions_triggering_policy_document" {
  statement {
    sid       = "StepFunctionsTriggeringPolicy"
    effect    = "Allow"
    resources = ["arn:aws:states:${var.aws_region}:${data.aws_caller_identity.current.account_id}:stateMachine:${aws_sfn_state_machine.ds_moments_state_machine_sf.name}"]
    actions   = ["states:StartExecution"]
  }
}

resource "aws_iam_policy" "step_functions_triggering_policy" {
  name        = "StepFunctions-${var.environment}-${var.service_name}-triggering-policy"
  description = "Allow triggering step functions"
  policy      = data.aws_iam_policy_document.step_functions_triggering_policy_document.json
}

resource "aws_iam_role_policy_attachment" "cloudwatch_step_functions_triggering_policy_attachment" {
  role       = aws_iam_role.ds_moments_step_functions_triggering_role.name
  policy_arn = aws_iam_policy.step_functions_triggering_policy.arn
}

resource "aws_cloudwatch_event_rule" "ds_moments_step_function_event_rule" {
  name                = "${var.environment}-${var.service_name}-trigger-state-machine-rule"
  description         = "The CloudWatch event rule for triggering AWS Step Functions flow"
  schedule_expression = "cron(1 1 5 5 ? *)"
  role_arn            = aws_iam_role.ds_moments_step_functions_triggering_role.arn
}

# Event target
resource "aws_cloudwatch_event_target" "cloudwatch_triggering_step_functions" {
  target_id = "run_scheduled_task"
  rule      = aws_cloudwatch_event_rule.ds_moments_step_function_event_rule.name
  arn       = aws_sfn_state_machine.ds_moments_state_machine_sf.id
  role_arn  = aws_iam_role.ds_moments_step_functions_triggering_role.arn
  input     = <<EOF
              {
                "chunk_count": "10",
                "step_1": "STEP1",
                "step_2": "STEP2",
                "step_3": "STEP3",
                "step_4": "STEP4",
                "step_5": "STEP5",
                "step_6": "STEP6",
                "folder": "path/to/folder",
                "run_id": "123456789012"
              }
              EOF
}
