locals {
  lambda_cloudwatch_event_dir = "lambda/cloudwatch-event"
  lambda_cloudwatch_event_hash = md5(join(",", [
    filemd5("${local.lambda_cloudwatch_event_dir}/index.py"),
    filemd5("${local.lambda_cloudwatch_event_dir}/requirements.txt"),
    filemd5("${local.lambda_cloudwatch_event_dir}/Dockerfile")
  ]))
}

resource "aws_ecr_repository" "lambda_cloudwatch_event_repository" {
  name                 = "${var.service_name}-cloudwatch-event"
  image_tag_mutability = "MUTABLE"

  encryption_configuration {
    encryption_type = "KMS"
  }

  image_scanning_configuration {
    scan_on_push = true
  }

  force_delete = true
}

resource "null_resource" "lambda_cloudwatch_event_build" {
  triggers = {
    src_hash = local.lambda_cloudwatch_event_hash
  }

  provisioner "local-exec" {
    command = "/bin/bash ./lambda/build-docker.sh"

    environment = {
      SRC_DIR             = local.lambda_cloudwatch_event_dir
      ECR_REPOSITORY_NAME = aws_ecr_repository.lambda_cloudwatch_event_repository.name
      ECR_REPOSITORY_TAG  = local.lambda_cloudwatch_event_hash
      ECR_REPOSITORY_URL  = aws_ecr_repository.lambda_cloudwatch_event_repository.repository_url
    }
  }
}

module "lambda_cloudwatch_event" {
  source = "../"

  environment        = var.environment
  lambda_name        = "${var.service_name}-cloudwatch-event"
  lambda_description = "Tests Lambda with Cloudwatch event trigger."
  application_family = "platform"

  use_container_image        = true
  container_image_custom_uri = "${aws_ecr_repository.lambda_cloudwatch_event_repository.repository_url}:${local.lambda_cloudwatch_event_hash}"

  vpc_id                = var.vpc_id
  vpc_subnet_ids        = var.vpc_subnet_ids
  vpc_enable_eni_lookup = false

  datadog_enabled          = true
  datadog_advanced_enabled = true

  cloudwatch_event_enabled = true
  cloudwatch_event_rules = [
    {
      name        = "${var.service_name}-rule-no-input"
      description = "Test Cloudwatch event lambda trigger with no input"
      schedule    = "rate(1 minute)"
    },
    {
      name        = "${var.service_name}-rule-with-input"
      description = "Test Cloudwatch event lambda trigger with static input"
      input = jsonencode({
        foo = "bar"
      })
      schedule = "rate(1 minute)"
    }
  ]

  lambda_function_environment_variables = {
    BUILD_ID = null_resource.lambda_cloudwatch_event_build.id
  }

  depends_on = [
    aws_ecr_repository.lambda_cloudwatch_event_repository
  ]
}
