# General Lambda variables
variable "environment" {
  description = "Name of the environment, e.g. dev, qa, prod"
  default     = "dev"
}

# DataDog settings.
variable "datadog_enabled" {
  description = "Whether or not to attach datadog secretsmanager IAM policy"
  default     = true
}

variable "datadog_advanced_enabled" {
  description = "Whether or not to gather metrics and traces. Allows using variables with datadog-advanced-* prefix."
  default     = true
}

variable "datadog_advanced_apm_enabled" {
  description = "Whether or not to send trace metrics to DataDog. Works only in advanced mode."
  default     = true
}

variable "datadog_advanced_appsec_sca_enabled" {
  description = "Whether or not to send runtime SCA metrics to DataDog. Works only in advanced mode."
  default     = true
}

variable "datadog_advanced_trace_enabled" {
  description = "Whether or not to send spans to DataDog. Works only in advanced mode."
  default     = true
}

variable "datadog_advanced_logs_injection_enabled" {
  description = "Whether or not to send logs to DataDog. Works only in advanced mode."
  default     = true
}

variable "datadog_advanced_merge_xray_traces_enabled" {
  description = "Whether or not to merge the X-Ray and dd-trace traces. Works only in advanced mode."
  default     = true
}

variable "datadog_advanced_api_key_secret_arn" {
  description = "Set custom arn for the secret with DD_API_KEY"
  default     = ""
}

variable "datadog_function_destination_lambda_name" {
  description = "Name of datadog function for shipping cloudwatch logs"
  default     = "DatadogLambdaFunction"
}

variable "datadog_lambda_library_arns" {
  description = <<EOT
                DataDog Lambda Library ARNs per environment. Check the latest versions here:
                - Python: https://github.com/DataDog/datadog-lambda-python/releases
                - NodeJS: https://github.com/DataDog/datadog-lambda-js/releases
                EOT
  type        = map(string)
  default = {
    "python3.13" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python313:111"
    "python3.12" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python312:111"
    "python3.11" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python311:111"
    "python3.10" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python310:111"
    "python3.9"  = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python39:64"
    "python3.8"  = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python38:64"
    "python3.7"  = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Python37:64"

    "nodejs22.x" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Node22-x:126"
    "nodejs20.x" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Node20-x:126"
    "nodejs18.x" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Node18-x:85"
    "nodejs16.x" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Node16-x:85"
    "nodejs14.x" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Node14-x:85"
    "nodejs12.x" = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Node12-x:85"
  }
}

variable "datadog_lambda_extension_arn" {
  description = <<EOT
                DataDog Lambda Extension ARN. Check the latest version here:
                  https://gallery.ecr.aws/datadog/lambda-extension
                EOT
  default     = "arn:aws:lambda:<AWS_REGION>:464622532012:layer:Datadog-Extension:34"
}

variable "enable_tracing" {
  description = "Whether to enable X-Ray tracing mode"
  type        = bool
  default     = true
}

# IAM settings.
variable "iam_policy_file_enabled" {
  description = "Does this function require additional IAM policies? If so specify a location in  the variable 'iam_policy_file_location'"
  default     = false
}

variable "iam_policy_file_location" {
  description = "path"
  default     = "policies"
}

variable "iam_managed_policy_attachments" {
  description = "List of ARNs of existing IAM policies to attach to role"
  type        = list(string)
  default     = []
}

variable "aws_region" {
  default = "us-east-1"
}

variable "lambda_name" {
  description = "Lambda function name, without environment prefix"
  default     = "lambda_function_name"
}

variable "application_family" {
  type        = string
  description = "Application family to which this service belongs"
}

variable "additional_tags" {
  type        = map(string)
  description = "Optional map of additional tags to set on resources. These will be combined with programmatically set required tags."
  default     = {}
}

variable "lambda_assume_role_service_identifiers" {
  description = "List of service identifiers for assume role trust relationship policy. Defaults are lambda and cloudwatch events"
  type        = list(string)
  default     = ["lambda.amazonaws.com", "events.amazonaws.com"]
}

variable "use_custom_function_name" {
  description = "Whether to use a custom function name; if so specify a name in var.custom_function_name"
  default     = false
}

variable "custom_function_name" {
  description = "User-provided function name if var.use_custom_function_name is set to true"
  default     = "my-custom-function-name"
}

variable "lambda_description" {
  description = "Lambda function description"
  default     = "This lambda does something very useful."
}

variable "lambda_function_environment_variables" {
  description = "Lambda function environment variables"
  type        = map(string)

  default = {
    Environment = "dev"
  }
}

variable "lambda_function_handler" {
  description = "Lambda function handler/entrypoint - only used for non-containerized Lambdas (set in Dockerfile for containerized ones)"
  default     = "index.handler"
}

variable "lambda_function_publish_version" {
  description = "Whether to configure function changes as new versions"
  default     = true
}

variable "lambda_function_timeout" {
  description = "Lambda fucntion timeout, in seconds"
  default     = "60"
}

variable "lambda_function_package_path" {
  description = "Path to lambda funtion. This should only be a dummy zip"
  default     = "lambda.zip"
}

variable "lambda_runtime" {
  description = "Runtime of lambda funtion"
  default     = "python3.12"
}

variable "lambda_function_memory_size" {
  description = "Amount of memory in MB your lambda function can use at runtime"
  default     = "128"
}

variable "lambda_function_ephemeral_storage_size" {
  description = "Amount of memory in MB your lambda function can use at runtime"
  default     = 512
}

variable "lambda_function_reserved_concurrent_executions" {
  description = "Number of reserved concurrent executions for lambda function"
  default     = "3"
}

variable "lambda_function_provisioned_concurrent_executions" {
  description = "Number of provisioned concurrent executions for lambda function. Puts lambda function to warm state, but may lead to high cost usage."
  default     = "0"
}

variable "lambda_function_provisioned_concurrency_alias" {
  description = "Alias to provisioned version."
  default     = "provisioned"
}

# CloudWatch settings.
variable "log_retention_in_days" {
  description = "Amount of days that we store logs for in CloudWatch."
  type        = number
  default     = 365
}

# VPC variables
variable "vpc_enabled" {
  description = "Enables VPC integration for lambda function."
  default     = true
}

variable "vpc_id" {
  description = "VPC ID for lambda function when VPC integration is enabled."
  type        = string
  default     = "vpc-34dbfd51"
}

variable "vpc_subnet_ids" {
  description = "Subnets in which to run lambda"
  type        = list(string)
  default     = ["subnet-b649dfef"]
}

variable "vpc_security_group_name" {
  description = "Set to use other security group than default one. If vpc_create_security_group is set, this one will be used as a fallback."
  type        = string
  default     = ""
}

variable "vpc_create_security_group" {
  type        = bool
  description = "Create a dedicated security group for the lambda function."
  default     = false

  validation {
    condition     = var.vpc_create_security_group ? var.vpc_enabled : true
    error_message = "Variable vpc_enabled must be set to true in order to use create_security_group."
  }
}

variable "vpc_enable_eni_lookup" {
  type        = bool
  description = "Enables ENI lookup for safe custom security group replacements. Disable it if you can't fetch data sources because module has depends_on option."
  default     = true
}

# Cloudwatch event variables
variable "cloudwatch_event_enabled" {
  description = "Whether or not to create a cloudwatch event to invoke lambda"
  default     = false
}

variable "cloudwatch_event_schedule" {
  description = "The schedule for cloudwatch event-based invocations. Specify a cron() or rate() expression. To specify multiple schedules or schedules with static input data, use the cloudwatch_event_rules variable instead."
  default     = "cron(0 0 * ? *)"
}

variable "cloudwatch_event_rules" {
  description = "A list of Cloudwatch Event rules to create. Takes precedence over cloudwatch_event_schedule."
  type = list(object(
    {
      name        = string
      schedule    = string
      description = optional(string)
      input       = optional(string)
    }
  ))
  default = []
}

# Event source mapping variables (for dynamodb and kinesis)
variable "event_source_mapping_enabled" {
  description = "Whether or not to create an event source mapping (for dynamodb and kinesis streams)"
  default     = false
}

variable "event_source_mapping_batch_size" {
  description = "Largest number of records that Lambda will retrieve from your event source (only for dynamo and kinesis triggers)"
  default     = "100"
}

variable "event_source_mapping_response_types" {
  description = "The desired response types for the event source mapping."
  type        = list(string)
  default     = null
}

variable "event_source_mapping_batch_window" {
  description = "Time in seconds to wait for batch to buffer"
  default     = null
}

variable "event_source_mapping_failure_arn" {
  description = "Destination ARN of SNS, S3 or SQS for failed invocations."
  default     = null
}

variable "event_source_mapping_parallelization_factor" {
  description = "The number of batches to process from each shard concurrently. Minimum and default of 1, maximum of 10. Only available for stream sources (DynamoDB and Kinesis)"
  default     = null
}

variable "event_source_mapping_resource_type" {
  description = "Select either dynamodb or kinesis for event_source_mapping"
  default     = "dynamodb"
}

variable "event_source_mapping_region" {
  description = "AWS region where event_source_mapping resource exists"
  default     = "us-east-1"
}

variable "event_source_mapping_stream_name" {
  description = "Stream name for event_source_mapping"
  default     = ""
}

variable "event_source_mapping_table_name" {
  description = "dynamodb table name for event_source_mapping. Not applicable for kinesis"
  default     = ""
}

variable "event_source_mapping_starting_position" {
  description = "Starting position for event_source_mapping. Can be one of TRIM_HORIZON, LATEST or AT_TIMESTAMP (Kinesis only)."
  default     = "TRIM_HORIZON"
}

variable "event_source_mapping_starting_position_timestamp" {
  description = "Starting position timestamp for event_source_mapping. Should be in RFC3339 format of the data record which to start reading when using starting_position set to AT_TIMESTAMP."
  default     = null
}

variable "event_source_mapping_bisect_batch_on_function_error" {
  description = "If the function returns an error, split the batch in two and retry"
  default     = false
}

variable "event_source_mapping_maximum_retry_attempts" {
  description = "The maximum number of times to retry when the function returns an error. Only available for stream sources (DynamoDB and Kinesis). Minimum and default of -1 (forever), maximum of 10000"
  default     = "-1"
}

variable "event_source_mapping_maximum_record_age_in_seconds" {
  description = "The maximum age of a record that Lambda sends to a function for processing. Only available for stream sources (DynamoDB and Kinesis). Must be either -1 (forever, and the default value) or between 60 and 604800 (inclusive)."
  default     = "-1"
}

variable "event_source_mapping_filter_criteria_pattern" {
  description = "A filter pattern up to 4096 characters"
  type        = string
  default     = ""
}

# S3 event variables
variable "s3_event_enabled" {
  description = "Whether or not to create an S3 event notification"
  default     = false
}

variable "s3_event_bucket_name" {
  description = "S3 bucket for notifications and lambda function executions"
  default     = "dev-bucket"
}

variable "s3_event_types" {
  description = "Specific S3 events used to trigger bucket notifications"
  type        = list(string)
  default     = ["s3:ObjectCreated:*"]
}

variable "s3_event_filter_prefix" {
  description = "Object prefix for S3 event key name, e.g. ows-service/"
  default     = ""
}

variable "s3_event_filter_suffix" {
  description = "Object suffix for S3 event key name, e.g. .csv"
  default     = ""
}

# SQS event variables
variable "sqs_event_enabled" {
  description = "Whether or not to create an SQS event notification"
  default     = false
}

variable "event_source_mapping_queue_name" {
  description = "SQS queue name for lambda function executions"
  default     = ""
}

# Kafka/MSK event variables
variable "kafka_topics" {
  type        = list(string)
  description = "List of Kafka topics to subscribe to."
  default     = []
}

variable "kafka_use_lambda_name_as_consumer_id" {
  type        = bool
  description = "Whether or not to use lambda name as consumer id."
  default     = false
}

variable "msk_event_enabled" {
  description = "Whether or not to have an MSK event invoke a lambda. If the MSK cluster is in a different AWS account, use kafka_event_enabled instead."
  default     = false
}

variable "event_source_mapping_msk_cluster_name" {
  description = "MSK cluster name for lambda function executions. Required if msk_event_enabled is set to true."
  default     = ""
}

variable "event_source_mapping_msk_cluster_uuid" {
  description = "MSK cluster UUID for lambda function executions (the last part of the cluster ARN). Required if msk_event_enabled is set to true."
  default     = ""
}

variable "kafka_event_enabled" {
  type        = bool
  description = <<EOF
  Whether or not to create an event source mapping for Kafka. If the Kafka cluster is an MSK cluster in the same AWS account, use msk_event_enabled instead.
  Use this for self-managed Kafka clusters or MSK clusters in other AWS accounts. For cross-account triggers, the MSK cluster security group must allow ingress
  from the Lambda subnets and security group.
EOF
  default     = false
}

variable "kafka_bootstrap_servers" {
  type        = list(string)
  description = "List of Kafka bootstrap servers to use if kafka_event_enabled is set to true. Not required if using msk_event_enabled."
  default     = []
}

# S3 settings
variable "zappa_s3_policy_enabled" {
  description = "Whether this function will pull down its deployments from a zappa-managed S3 location"
  default     = false
}

variable "use_s3_source" {
  description = "Whether to use a zip held in an Orchard-owned S3 bucket"
  default     = false
}

variable "s3_source_bucket" {
  default = "lambda-deployment-bucket"
}

variable "custom_s3_source_key" {
  default = ""
}

# Container Image settings
variable "container_image_custom_uri" {
  description = "Custom URI for container image. Changes to the container image URI are ignored by this module to allow deployments to be performed outside of Terraform, so by default the function will use a dummy placeholder image on creation. Only override this if your function uses a static image."
  default     = ""
}

variable "use_container_image" {
  description = "Whether or not to use a container image. Cannot be mixed with s3_source or local zip deployments. Changes to the container image URI are ignored by this module to allow deployments to be performed outside of Terraform, so by default the function will use a dummy placeholder image on creation. Set var.container_image_custom_uri to use a custom image."
  default     = false
}

variable "lambda_deployable_version" {
  default = ""
}

# Lambda layers.
variable "lambda_layers" {
  description = "List of lambda layer ARNs, up to 5."
  default     = []
}

# Dead-letter queue variables
variable "dlq_enabled" {
  description = "Enables dead-letter queue for lambda function."
  default     = true
}

variable "dlq_type" {
  description = "The type of dead-letter queue to use. Set to either SNS or SQS."
  default     = "sns"
}

variable "dlq_sqs_fifo_queue" {
  description = "If set to `true` the order in which messages are sent and received is strictly preserved. Also sets value for content_based_deduplication."
  default     = "false"
}

variable "dlq_sqs_max_message_size" {
  description = "The minimum message size is 1 byte (1 character). The maximum is 262,144 bytes (256 KB)."
  default     = 2048
}

variable "dlq_sqs_message_retention_seconds" {
  description = "By default, a message is retained for 4 days. The minimum is 60 seconds (1 minute). The maximum is 1,209,600 seconds (14 days)."
  default     = 86400
}

variable "dlq_sqs_visibility_timeout_seconds" {
  description = "The visibility timeout for the queue. An integer from 0 to 43200 (12 hours)."
  default     = 30
}

variable "dlq_sqs_kms_data_key_reuse_period_seconds" {
  description = "The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again."
  default     = 300
}

variable "ows_machine_to_machine_enabled" {
  description = "Whether or not to attach ows machine-to-machine secretsmanager IAM policy"
  default     = true
}

variable "splitio_enabled" {
  description = "Whether or not to attach Split secretsmanager IAM policy."
  default     = true
}

# EFS settings.
variable "efs_enabled" {
  description = "Whether or not to attach EFS to lambda function."
  default     = false
}

variable "efs_access_point_arn" {
  description = "ARN of the EFS access point to attach to lambda."
  default     = ""
}

variable "efs_local_mount_path" {
  description = "Mount path of the EFS to attach to lambda. Should start with '/mnt/' and be exactly the same as the EFS access point path."
  default     = "/mnt/efs"
}

# Delay settings.
variable "existing_iam_policy_attachments_propagation_delay" {
  default = "30s"
}

variable "efs_access_point_propagation_delay" {
  default = "30s"
}

variable "architectures" {
  description = "Architecture for the lambda's runtime. Valid values: x86_64 and arm64"
  type        = list(string)
  default     = ["x86_64"]
}

variable "permissions_boundary_enabled" {
  type        = bool
  description = <<EOF
  Whether or not to set a permissions boundary to limit the permissions of IAM roles created by this module.
  By default, this is true in dev (to allow local Terraform execution) and false in other environments.
  It may be necessary to set this to false in dev if the IAM roles require permissions in excess of those allowed by the permissions boundary policy.
  However, doing so will restrict the ability to run Terraform locally.
EOF
  default     = null
}

variable "permissions_boundary_policy_name" {
  type        = string
  description = "The name of the policy to use as the permissions boundary for the IAM roles created by this module, if permissions_boundary_enabled is true."
  default     = "dev-permissions-boundary-policy"
}

variable "replace_security_groups_on_destroy" {
  type        = bool
  description = "Whether to replace the security groups on the function's VPC configuration prior to destruction if create_security_group is set."
  default     = true
}

# Helper locals for programmatic generation. These should not be changed.
locals {
  ows_machine_to_machine_manager_policy_arn = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/SecretsManager-${var.environment}-ows-machine-to-machine-policy"
  datadog_secrets_manager_policy_arn        = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/SecretsManager-${var.environment}-datadog-policy"
  datadog_function_destination_arn          = "arn:aws:lambda:${var.aws_region}:${data.aws_caller_identity.current.account_id}:function:${var.datadog_function_destination_lambda_name}"
  # Prerender lambda function name
  generated_function_name = "${var.environment}-${var.lambda_name}"

  # Construct ARNs for dynamodb and kinesis sources
  event_source_mapping_arn = {
    dynamodb = "arn:aws:dynamodb:${var.event_source_mapping_region}:${data.aws_caller_identity.current.account_id}:table/${var.event_source_mapping_table_name}/stream/${var.event_source_mapping_stream_name}"
    kinesis  = "arn:aws:kinesis:${var.event_source_mapping_region}:${data.aws_caller_identity.current.account_id}:stream/${var.event_source_mapping_stream_name}"
    sqs      = "arn:aws:sqs:${var.event_source_mapping_region}:${data.aws_caller_identity.current.account_id}:${var.event_source_mapping_queue_name}"
    msk      = "arn:aws:kafka:${var.event_source_mapping_region}:${data.aws_caller_identity.current.account_id}:cluster/${var.event_source_mapping_msk_cluster_name}/${var.event_source_mapping_msk_cluster_uuid}"
  }
  # Construct resource ARNS to use with IAM policy for dynamodb, kinesis sources
  event_source_mapping_iam_resource_arn = {
    dynamodb = "arn:aws:dynamodb:${var.event_source_mapping_region}:${data.aws_caller_identity.current.account_id}:table/${var.event_source_mapping_table_name}/stream/*"
    kinesis  = "arn:aws:kinesis:${var.event_source_mapping_region}:${data.aws_caller_identity.current.account_id}:stream/${var.event_source_mapping_stream_name}"
  }

  function_name = var.use_custom_function_name ? var.custom_function_name : local.generated_function_name

  // If a version is provided, the s3 source key will be of the form <env>/<lambda-name>-<version>.zip,
  // Otherwise, it can be a custom provided key, or else it will be set to an empty string. If empty, see `use_s3_source`
  s3_source_key = length(var.custom_s3_source_key) > 0 || length(var.lambda_deployable_version) == 0 ? var.custom_s3_source_key : "${var.environment}/${var.lambda_name}-${var.lambda_deployable_version}.zip"

  // In order to use an s3 source, we need to specify that we want to do so when invoking the lambda module,
  // and provide non-zero-length strings for bucket and key
  use_s3_source = length(local.s3_source_key) * length(var.s3_source_bucket) > 0 && var.use_s3_source

  // Unless container image URI specified explicitly, use a dummy image as the initial value as Lambda deployments are handled outside of Terraform.
  // By using a dummy image by default we remove the need for an image to be published prior to creating a function.
  default_ecr_registry_id     = "086679231553" // Shared services account
  default_ecr_repository_name = "dummy"
  default_container_image_uri = "${local.default_ecr_registry_id}.dkr.ecr.${var.aws_region}.amazonaws.com/${local.default_ecr_repository_name}:latest"
  container_image_uri         = length(var.container_image_custom_uri) > 0 ? var.container_image_custom_uri : local.default_container_image_uri

  // ===== Provisioned Concurrency settings =====
  provisioned_concurrency_enabled = var.lambda_function_provisioned_concurrent_executions > 0 ? true : false
  publish_version                 = local.provisioned_concurrency_enabled ? true : var.lambda_function_publish_version

  // ===== DataDog advanced settings =====

  // Enable advanced features when datadog_enabled and datadog_advanced_enabled variables both are true.
  datadog_advanced_enabled = var.datadog_enabled && var.datadog_advanced_enabled

  // Enable lambda layers support only for non-containerized lambdas.
  datadog_lambda_layers_enabled = local.datadog_advanced_enabled && !var.use_container_image

  // Get lambda runtime name without version specifics. Fallback to null on non-supported runtime.
  datadog_lambda_runtime = local.datadog_advanced_enabled ? (
    substr(var.lambda_runtime, 0, 6) == "python" ? "python" : (
      substr(var.lambda_runtime, 0, 6) == "nodejs" ? "nodejs" : null
    )
  ) : null

  // Replace AWS region name template in layers with the selected region.
  datadog_lambda_library_layer   = local.datadog_lambda_layers_enabled ? replace(var.datadog_lambda_library_arns[var.lambda_runtime], "<AWS_REGION>", var.aws_region) : null
  datadog_lambda_extension_layer = local.datadog_lambda_layers_enabled ? replace(var.datadog_lambda_extension_arn, "<AWS_REGION>", var.aws_region) : null

  // Add DataDog layers to lambda.
  datadog_lambda_layers = local.datadog_lambda_layers_enabled ? [local.datadog_lambda_library_layer, local.datadog_lambda_extension_layer] : []

  // Set DataDog tags delimiter. It's different for some runtimes.
  datadog_tags_delimiter = local.datadog_lambda_runtime == "python" ? " " : (
    local.datadog_lambda_runtime == "nodejs" ? "," : " "
  )

  // Use default dd_api_key secret arn if it hasn't been set explicitly
  datadog_advanced_api_key_secret_arn = (
    var.datadog_advanced_api_key_secret_arn == "" ?
    "arn:aws:secretsmanager:${var.aws_region}:${data.aws_caller_identity.current.account_id}:secret:${var.environment}/datadog/DD_API_KEY" :
    var.datadog_advanced_api_key_secret_arn
  )

  // Configure DataDog-related environment variables.
  datadog_lambda_environment_variables = local.datadog_advanced_enabled ? {
    DD_SITE               = "datadoghq.com"
    DD_API_KEY_SECRET_ARN = local.datadog_advanced_api_key_secret_arn
    DD_ENV                = var.environment
    DD_SERVICE            = var.lambda_name
    DD_TAGS               = join(",", [for k, v in local.combined_resource_tags : "${k}:${v}"])
    # DD_LAMBDA_HANDLER env var set in Docker file for containizered lambdas
    DD_LAMBDA_HANDLER     = !var.use_container_image ? var.lambda_function_handler : null
    DD_APM_ENABLED        = var.datadog_advanced_apm_enabled
    DD_APPSEC_SCA_ENABLED = var.datadog_advanced_appsec_sca_enabled
    DD_TRACE_ENABLED      = var.datadog_advanced_trace_enabled
    DD_LOGS_INJECTION     = var.datadog_advanced_logs_injection_enabled
    DD_MERGE_XRAY_TRACES  = var.datadog_advanced_merge_xray_traces_enabled && var.enable_tracing
  } : {}

  // Change lambda function handler passed to AWS Lambda to DataDog library for non-containerized lambdas
  lambda_function_handler = local.datadog_lambda_runtime == "python" ? "datadog_lambda.handler.handler" : (
    local.datadog_lambda_runtime == "nodejs" ? "/opt/nodejs/node_modules/datadog-lambda-js/handler.handler" : var.lambda_function_handler
  )

  // Set minimum memory_size to 256MB when DataDog advanced features are enabled.
  lambda_function_memory_size = local.datadog_advanced_enabled && var.lambda_function_memory_size < 256 ? 256 : var.lambda_function_memory_size

  // Merge DataDog layers with lambda layers.
  lambda_layers = distinct(concat(local.datadog_lambda_layers, var.lambda_layers))

  // Merge DataDog-related environment variables with lambda envs.
  lambda_function_environment_variables = merge(local.datadog_lambda_environment_variables, var.lambda_function_environment_variables)

  // Enable CloudWatch log subscription when advanced features are disabled.
  cloudwatch_log_subscription_enabled = var.datadog_enabled && !var.datadog_advanced_enabled

  # Concatenate required and user-supplied tags
  combined_resource_tags = merge(
    {
      environment        = var.environment
      service_name       = var.lambda_name
      env                = var.environment # datadog expects env defined as this tag
      service            = var.lambda_name # datadog expects service defined as this tag
      application_family = var.application_family
      terraformed        = true
    },
    var.additional_tags
  )
  lambda_function_arn = local.provisioned_concurrency_enabled ? aws_lambda_alias.provisioned[0].arn : aws_lambda_function.function.arn

  # If cloudwatch event enabled and explicit list of rules provided, use that,
  # otherwise default to a single rule based on the cloudwatch_event_schedule variable.
  cloudwatch_event_rules = var.cloudwatch_event_enabled ? coalescelist(var.cloudwatch_event_rules, [
    {
      name     = var.lambda_name
      schedule = var.cloudwatch_event_schedule
    }
  ]) : []

  permissions_boundary_enabled = coalesce(var.permissions_boundary_enabled, var.environment == "dev" ? true : false)
  permissions_boundary_arn     = local.permissions_boundary_enabled ? data.aws_iam_policy.permissions_boundary_policy[0].arn : null

  primsa_sg_exception_tags = {
    "eiso-exception" = "aws.08.30"
  }

  replace_security_groups_on_destroy = var.vpc_create_security_group ? var.replace_security_groups_on_destroy : null
  default_security_group             = "${var.environment}-lambda-default-security-group"

  tracing_mode = var.enable_tracing ? "Active" : "PassThrough"
}
