locals {
  lambda_arn = "arn:aws:lambda:${var.region}:${var.account_id}:function:${var.function_name}"
}

resource "random_string" "scheduler_id" {
  length  = 5
  special = false
}

resource "aws_cloudwatch_event_rule" "this" {
  name                = var.name == "" ? "${var.function_name}-${random_string.scheduler_id.result}" : var.name
  description         = "${var.function_name} scheduler ${random_string.scheduler_id.result}"
  schedule_expression = var.schedule_expression
  is_enabled          = var.is_enabled

  lifecycle {
    ignore_changes = [is_enabled]
  }
}

resource "aws_cloudwatch_event_target" "this" {
  rule  = aws_cloudwatch_event_rule.this.name
  arn   = local.lambda_arn
  input = var.input
}

resource "aws_lambda_permission" "this" {
  statement_id_prefix = "AllowExecutionFromCloudWatch${random_string.scheduler_id.result}"
  action              = "lambda:InvokeFunction"
  function_name       = var.function_name
  principal           = "events.amazonaws.com"
  source_arn          = aws_cloudwatch_event_rule.this.arn
}
