# EventBridge Rule to trigger AWS Step Functions on a schedule
resource "aws_cloudwatch_event_rule" "ds_moments_event_rule" {
  name                = "${var.environment}-${var.service_name}-scheduler"
  description         = "Triggers AWS Step Functions execution on a schedule."
  schedule_expression = "cron(0 11 ? * MON *)"
  state               = "DISABLED"
}

data "aws_iam_policy_document" "ds_moments_scheduler_iam_role_assume_policy" {
  version = "2012-10-17"
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      identifiers = ["events.amazonaws.com"]
      type        = "Service"
    }
    effect = "Allow"
  }
}

# IAM Role for EventBridge to invoke Step Functions
resource "aws_iam_role" "ds_moments_scheduler_iam_role" {
  name = "${var.environment}-${var.service_name}-schedule-execution-role"

  assume_role_policy = data.aws_iam_policy_document.ds_moments_scheduler_iam_role_assume_policy.json
}

data "aws_iam_policy_document" "ds_moments_iam_policy_document" {
  version = "2012-10-17"

  statement {
    actions   = ["states:StartExecution"]
    resources = [aws_sfn_state_machine.sfn_ds_moments_pipeline.arn]
    effect    = "Allow"
  }
}

# IAM policy to grant the role permission to invoke Step Functions
resource "aws_iam_role_policy" "ds_moments_iam_policy" {
  name = "EventBridge-${var.environment}-${var.service_name}-execution-policy"
  role = aws_iam_role.ds_moments_scheduler_iam_role.id

  policy = data.aws_iam_policy_document.ds_moments_iam_policy_document.json
}

# EventBridge target that invokes the Step Functions state machine
resource "aws_cloudwatch_event_target" "step_function_target" {
  rule     = aws_cloudwatch_event_rule.ds_moments_event_rule.name
  arn      = aws_sfn_state_machine.sfn_ds_moments_pipeline.arn
  role_arn = aws_iam_role.ds_moments_scheduler_iam_role.arn

  input_transformer {
    input_paths = {
      "time" = "$.time",
    }

    input_template = "{\"time\": <time>}"
  }
}
