locals {
  full_service_name = "${var.service_name}-${var.lambda_name}"
  efs_volumes = merge(
    { for p in var.audio_encoding_priorities : "delivery-audio-p${p}" => {} },
    { for p in var.video_encoding_priorities : "delivery-video-p${p}" => {} },
  )
}

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       = local.full_service_name
  team_name          = var.team_name
}

provider "aws" {
  region = var.region

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/lambda-vector/cleanup-efs/terraform.tfstate"
    region  = "us-east-1"
    encrypt = true
  }
}

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

  environment = var.environment
}

# Shared subnet lookup — all EFS volumes are in the same subnets
data "aws_subnets" "efs_subnets" {
  filter {
    name   = "vpc-id"
    values = [module.vpc_info.vpc_id]
  }
  filter {
    name   = "tag:Name"
    values = ["prod_vector_subnet_*"]
  }
}

# EFS data sources — look up each target EFS volume
data "aws_efs_file_system" "target" {
  for_each       = local.efs_volumes
  creation_token = "${var.environment}-${var.efs_base_service_name}-${each.key}"
}

data "aws_efs_access_points" "target" {
  for_each       = local.efs_volumes
  file_system_id = data.aws_efs_file_system.target[each.key].id
}

data "aws_efs_access_point" "target" {
  for_each        = local.efs_volumes
  access_point_id = one(data.aws_efs_access_points.target[each.key].ids)
}

data "aws_security_group" "efs" {
  for_each = local.efs_volumes
  name     = "${var.environment}-${var.efs_base_service_name}-${each.key}-efs-security-group"
  vpc_id   = module.vpc_info.vpc_id
}

data "aws_iam_policy" "efs" {
  for_each = local.efs_volumes
  name     = "EFS-${var.environment}-${var.efs_base_service_name}-${each.key}-policy"
}

# Look up the SG created by each lambda module instance
data "aws_security_group" "lambda" {
  for_each   = local.efs_volumes
  name       = "${var.environment}-${local.full_service_name}-${each.key}-lambda-security-group"
  vpc_id     = module.vpc_info.vpc_id
  depends_on = [module.lambda_cleanup_efs]
}

# Allow each lambda SG to reach its corresponding EFS
resource "aws_security_group_rule" "efs_allow_lambda" {
  for_each                 = local.efs_volumes
  type                     = "ingress"
  from_port                = 2049
  to_port                  = 2049
  protocol                 = "tcp"
  security_group_id        = data.aws_security_group.efs[each.key].id
  source_security_group_id = data.aws_security_group.lambda[each.key].id
}

module "lambda_cleanup_efs" {
  for_each = local.efs_volumes
  source   = "git@github.com:theorchard/terraform-lambda.git//?ref=5.2.2"

  environment         = var.environment
  application_family  = var.application_family
  use_container_image = true
  lambda_name         = "${local.full_service_name}-${each.key}"
  lambda_description  = "Cleans up old EFS directories based on a retention period"

  lambda_function_timeout                        = var.lambda_timeout
  lambda_function_reserved_concurrent_executions = 1

  vpc_enabled               = true
  vpc_subnet_ids            = data.aws_subnets.efs_subnets.ids
  vpc_id                    = module.vpc_info.vpc_id
  vpc_create_security_group = true

  efs_enabled          = true
  efs_access_point_arn = data.aws_efs_access_point.target[each.key].arn
  efs_local_mount_path = var.efs_mount_path

  cloudwatch_event_enabled  = true
  cloudwatch_event_schedule = "cron(0 0 * * ? *)"

  datadog_enabled          = true
  datadog_advanced_enabled = true

  splitio_enabled                = false
  ows_machine_to_machine_enabled = false

  iam_managed_policy_attachments = [
    data.aws_iam_policy.efs[each.key].arn,
  ]

  lambda_function_environment_variables = {
    EFS_PATH           = var.efs_mount_path
    EFS_RETENTION_DAYS = tostring(var.efs_retention_days)
    SENTRY_DSN         = module.sentry_cleanup_efs.sentry_key_dsn_public_output
  }
}

# Shared Sentry project for all lambda instances
module "sentry_cleanup_efs" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=5.0.0"

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

# Per-instance Datadog monitors (each lambda has distinct CloudWatch metrics)
module "datadog_cleanup_efs" {
  for_each = local.efs_volumes
  source   = "git@github.com:theorchard/terraform-datadog.git//modules/lambda?ref=6.17.1"

  environment                       = var.environment
  service_name                      = "${local.full_service_name}-${each.key}"
  lambda_invocation_monitor_enabled = false
  lambda_error_monitor_enabled      = true
  notification_endpoints            = var.notification_endpoints
}
