resource "aws_iam_role" "dynamodb_refresh_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 = [aws_sfn_state_machine.sfn_dynamodb_refresh.arn]
    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.dynamodb_refresh_step_functions_triggering_role.name
  policy_arn = aws_iam_policy.step_functions_triggering_policy.arn
}

resource "aws_cloudwatch_event_rule" "backup_job_status" {
  name = "backup-copy-complete-event-rule"
  event_pattern = jsonencode({
    detail-type = [
      "Recovery Point State Change"
    ]
    detail = {
      backupVaultArn = [module.dynamodb_vault.vault_arn]
      status         = ["COMPLETED"]
    }
  })

  tags = local.tags
}

resource "aws_cloudwatch_event_target" "lambda_copy_recovery_point" {
  arn      = aws_sfn_state_machine.sfn_dynamodb_refresh.arn
  rule     = aws_cloudwatch_event_rule.backup_job_status.name
  role_arn = aws_iam_role.dynamodb_refresh_step_functions_triggering_role.arn
}
