data "aws_iam_policy_document" "assume_roles_for_events_policy" {
  statement {
    sid = "AllowCWEServiceToAssumeRole"

    actions = [
      "sts:AssumeRole",
    ]

    principals {
      type = "Service"

      identifiers = [
        "events.amazonaws.com",
      ]
    }
  }
}

#  Policy for starting execution initiated by a CloudWatch rule.
data "aws_iam_policy_document" "start_executions_policy" {
  statement {
    effect = "Allow"

    actions = [
      "states:StartExecution",
    ]

    resources = [
      aws_sfn_state_machine.hfa_request_file.arn,
    ]
  }
}

# CloudWatch event rule role for starting execution
resource "aws_iam_role" "execute_state_machine_roles" {
  name               = "${var.environment}-hfa-request-file-execute-state-machine"
  assume_role_policy = data.aws_iam_policy_document.assume_roles_for_events_policy.json
}

resource "aws_iam_role_policy" "start_execution_roles_policy" {
  name   = "${var.environment}-hfa-request-file-execute-state-machine"
  role   = aws_iam_role.execute_state_machine_roles.id
  policy = data.aws_iam_policy_document.start_executions_policy.json
}

# Event rule for hfa_request_file.
resource "aws_cloudwatch_event_rule" "hfa_request_file_event_rule" {
  name                = "${var.environment}-hfa-request-file-event-rule"
  description         = "The CloudWatch event rule for hfa request file"
  schedule_expression = "cron(0/15 * * * ? *)"
  state               = "ENABLED"
}

resource "aws_cloudwatch_event_target" "hfa_request_file_state_machine_target" {
  rule      = aws_cloudwatch_event_rule.hfa_request_file_event_rule.name
  target_id = "${var.environment}_hfa_request_file_event_rule_target"
  arn       = aws_sfn_state_machine.hfa_request_file.arn
  role_arn  = aws_iam_role.execute_state_machine_roles.arn
}
