module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = "devops"
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "dev-orcd-terraform-state"
    key     = "dev/datadog-s3-event-forwarder/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

module "sentry" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=5.1.0"

  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  teams              = [var.environment]
}

module "lambda" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=5.3.0"

  environment        = var.environment
  lambda_name        = var.service_name
  application_family = var.application_family
  lambda_description = "Publishes S3 event notifications to Datadog."

  lambda_function_memory_size                    = var.lambda_memory_size
  lambda_function_timeout                        = var.lambda_timeout
  lambda_function_reserved_concurrent_executions = var.lambda_reserved_concurrent_executions

  use_container_image            = true
  datadog_advanced_enabled       = true
  vpc_enabled                    = false
  zappa_s3_policy_enabled        = false
  splitio_enabled                = false
  ows_machine_to_machine_enabled = false

  lambda_function_environment_variables = {
    Environment = var.environment
    SENTRY_DSN  = module.sentry.sentry_key_dsn_public_output
  }
}

resource "aws_lambda_permission" "allow_s3_trigger" {
  statement_id   = "allow-s3-trigger"
  principal      = "s3.amazonaws.com"
  source_account = data.aws_caller_identity.current.account_id
  action         = "lambda:InvokeFunction"
  function_name  = module.lambda.lambda_name
}
