locals {
  sfn_name      = "sfn-content-index-product-metadata"
  lambda_prefix = "arn:aws:lambda:${var.aws_region}:${data.aws_caller_identity.current.account_id}:function:${var.environment}-${var.service_name}"
}

# Step Function (SFN) root role policy document.
data "aws_iam_policy_document" "sfn_content_index_product_metadata_assume_role" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "Service"
      identifiers = [
        "states.amazonaws.com",
        "lambda.amazonaws.com",
        "events.amazonaws.com"
      ]
    }
  }
}

resource "aws_iam_role" "sfn_content_index_product_metadata_assume_role" {
  name               = "${var.environment}-${local.sfn_name}-state-machine-role"
  assume_role_policy = data.aws_iam_policy_document.sfn_content_index_product_metadata_assume_role.json
}

# State machine lambda policy that gives the state machine role permission to invoke lambdas
data "aws_iam_policy_document" "sfn_content_index_product_metadata_lambda_policy_document" {
  statement {
    actions = [
      "lambda:InvokeFunction",
    ]

    resources = [
      "${local.lambda_prefix}-*"
    ]
  }
}

resource "aws_iam_role_policy" "sfn_content_index_product_metadata_invoke_lambda_role_policy" {
  name   = "${var.environment}-${local.sfn_name}-lambda-role-policy"
  role   = aws_iam_role.sfn_content_index_product_metadata_assume_role.id
  policy = data.aws_iam_policy_document.sfn_content_index_product_metadata_lambda_policy_document.json
}

resource "aws_cloudwatch_log_group" "sfn_log_group" {
  name              = "/aws/vendedlogs/states/${var.environment}-${local.sfn_name}-log-group"
  retention_in_days = 365
  tags = {
    application_family = var.application_family
    environment        = var.environment
    service_name       = local.sfn_name
    terraformed        = true
  }
}

data "aws_lambda_function" "datadog_lambda_function" {
  function_name = "DatadogLambdaFunction"
}

resource "aws_cloudwatch_log_subscription_filter" "datadog_lambda_log_filter" {
  name            = "${var.environment}-${local.sfn_name}-log-group-subscription-filter"
  log_group_name  = aws_cloudwatch_log_group.sfn_log_group.name
  filter_pattern  = ""
  destination_arn = data.aws_lambda_function.datadog_lambda_function.arn
  distribution    = "ByLogStream"
}

# Step Function (SFN) - SFN Cloudwatch logs permission policy
data "aws_iam_policy_document" "sfn_content_index_product_log_event_policy_document" {
  # checkov:skip=CKV_AWS_111:not all Cloudwatch API actions support resources types

  statement {
    effect = "Allow"
    resources = [
      "arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:log-group:${var.environment}-${local.sfn_name}",
      "arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:log-group:${var.environment}-${local.sfn_name}:log-stream:*",
      "${aws_cloudwatch_log_group.sfn_log_group.arn}:*"
    ]

    actions = [
      "logs:CreateLogGroup",
      "logs:CreateLogStream",
      "logs:PutLogEvents"
    ]
  }

  statement {
    effect    = "Allow"
    resources = ["*"]
    actions = [
      "logs:CreateLogDelivery",
      "logs:DeleteLogDelivery",
      "logs:DescribeLogGroups",
      "logs:DescribeResourcePolicies",
      "logs:GetLogDelivery",
      "logs:ListLogDeliveries",
      "logs:PutResourcePolicy",
      "logs:UpdateLogDelivery",
      "logs:DeleteLogGroup",
      "logs:DeleteLogStream"
    ]
  }
}

resource "aws_iam_policy" "sfn_content_index_product_log_event_policy" {
  name        = "${var.environment}-${local.sfn_name}-log-event-policy"
  description = "Policy for Step Function to write logs to CloudWatch"
  policy = data.aws_iam_policy_document.sfn_content_index_product_log_event_policy_document.json
}

resource "aws_iam_role_policy_attachment" "sfn_content_index_product_log_event_policy_attachment" {
  role       = aws_iam_role.sfn_content_index_product_metadata_assume_role.name
  policy_arn = aws_iam_policy.sfn_content_index_product_log_event_policy.arn
}

# Template for state machine.
data "template_file" "sfn_content_index_product_metadata_definition" {
  template = file("${path.module}/sfn.json")
  vars = {
    lambda_prefix = local.lambda_prefix
  }
}

resource "aws_sfn_state_machine" "sfn_content_index_product_metadata" {
  name       = "${var.environment}-${local.sfn_name}"
  role_arn   = aws_iam_role.sfn_content_index_product_metadata_assume_role.arn
  definition = data.template_file.sfn_content_index_product_metadata_definition.rendered

  tags = {
    application_family = var.application_family
    environment        = var.environment
    env                = var.environment
    service_name       = local.sfn_name
    service            = local.sfn_name
    DD_TRACE_ENABLED   = true
    terraformed        = true
  }

  logging_configuration {
    log_destination        = "${aws_cloudwatch_log_group.sfn_log_group.arn}:*"
    include_execution_data = true
    level                  = "ALL"
  }
  tracing_configuration {
    enabled = true
  }
} 

module "datadog_sfn_dashboard" {
  source             = "git@github.com:theorchard/terraform-datadog.git//modules/step-function?ref=6.13.9"
  environment        = var.environment
  service_name       = local.sfn_name
  application_family = var.application_family
  statemachine_arn   = aws_sfn_state_machine.sfn_content_index_product_metadata.arn

  failed_execution_message_log_monitor = {
    enabled        = true
    log_group_name = aws_cloudwatch_log_group.sfn_log_group.name
  }
  notification_endpoints            = var.notification_endpoints
  escalation_notification_endpoints = var.escalation_notification_endpoints
}
