data "aws_iam_policy_document" "assume_role_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_execution_policy" {
  statement {
    effect = "Allow"

    actions = [
      "states:StartExecution",
    ]

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

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

resource "aws_iam_role_policy" "start_execution_role_policy" {
  name   = "${var.environment}-populate-hfa-pending-request-execute-state-machine"
  role   = aws_iam_role.execute_state_machine_role.id
  policy = data.aws_iam_policy_document.start_execution_policy.json
}

# Event rule for populate_hfa_pending_request.
resource "aws_cloudwatch_event_rule" "populate_hfa_pending_request_event_rule" {
  name          = "${var.environment}-populate-hfa-pending-request-event-rule"
  description   = "The CloudWatch event rule for populate hfa pending request"
  schedule_expression  = "cron(0 3 * * ? *)"
}

resource "aws_cloudwatch_event_target" "populate_hfa_pending_request_state_machine_target" {
  rule      = aws_cloudwatch_event_rule.populate_hfa_pending_request_event_rule.name
  target_id = "${var.environment}_populate_hfa_pending_request_event_rule_target"
  arn       = aws_sfn_state_machine.populate_hfa_pending_request.arn
  role_arn      = aws_iam_role.execute_state_machine_role.arn
}
