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

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "prod/datadog/security-notification-rules/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "datadog_teams" "all_teams" {}

locals {
  team_config = {
    "devops" = {
      enabled      = true
      jira_project = "DevOps"
    }
  }

  enabled_teams = {
    for team in data.datadog_teams.all_teams.teams : team.handle => lookup(local.team_config, team.handle, {})
    if lookup(lookup(local.team_config, team.handle, {}), "enabled", false)
  }
}

resource "datadog_security_notification_rule" "vulnerability_rule" {
  for_each = local.enabled_teams

  name = "Security Vulnerability Notifications (${each.key})"
  selectors {
    trigger_source = "security_findings"
    rule_types     = ["application_library_vulnerability"]
    severities     = ["critical", "high"]
    # Exclude "Risky license" findings as these are not strictly vulnerabilities, so they are
    # liable to create noise and we have different expectations around handling them.
    query = "team:${each.key} -type:\"Risky license\""
  }
  # Create a separate Jira issue for each vulnerability finding
  time_aggregation = 0
  targets          = ["@jira-${each.value.jira_project}"]
}
