provider "aws" {
  region = var.aws_region
}

terraform {
  backend "s3" {
    bucket  = "prod-fansifter-terraform-state"
    key     = "prod/lambda-audience/refresh-m2m-token/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git?ref=1.0.0"

  environment = var.environment
}

module "lambda" {
  source                  = "git@github.com:theorchard/terraform-lambda.git//?ref=3.1.4"
  lambda_name             = var.lambda_name
  lambda_description      = "Lambda to refresh Auth0 M2M JWT token for Fansifter-${upper(var.environment)} account"
  lambda_function_timeout = 120
  environment             = var.environment
  application_family      = var.application_family

  lambda_function_memory_size = 256

  vpc_enabled    = true
  vpc_id         = module.vpc_info.vpc_id
  vpc_subnet_ids = module.vpc_info.default_private_subnet_ids

  use_container_image = true

  datadog_advanced_enabled = true

  lambda_function_environment_variables = {
    ENVIRONMENT         = var.environment
    SENTRY_DSN          = module.sentry.sentry_key_dsn_public_output
    AUTH0_M2M_CLIENT_ID = var.auth0_m2m_client_id
  }

  cloudwatch_event_enabled  = true
  cloudwatch_event_schedule = "rate(8 hours)"

  iam_managed_policy_attachments = [
    aws_iam_policy.secrets_manager_extra_policy.arn,
  ]
}

module "sentry" {
  source             = "git@github.com:theorchard/terraform-sentry.git//?ref=4.0.2"
  service_name       = var.lambda_name
  environment        = var.environment
  application_family = var.application_family
  teams              = [var.environment]
  platform           = "python"
}

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

  environment                       = var.environment
  service_name                      = var.lambda_name
  teams                             = ["fansifter"]
  lambda_invocation_monitor_enabled = false

  notification_endpoints            = "@slack-fansifter-alerts"
  escalation_notification_endpoints = "@slack-fansifter"
}

module "secrets" {
  source   = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.2.1"
  for_each = toset(var.secrets_manager_secret_names)

  application_family = var.application_family
  environment        = var.environment
  service_name       = var.lambda_name
  secret_name        = each.value
}
