// Sentry project for the lambda
// The SENTRY_DSN will be stored in AWS Secrets Manager

module "lambda_sentry_project" {
  source = "git@github.com:theorchard/terraform-sentry//?ref=4.0.1"

  environment        = var.environment
  teams              = var.sentry_teams
  service_name       = var.lambda_name
  application_family = var.application_family
  platform           = var.sentry_platform
}

# Retrieve a Slack integration
data "sentry_organization_integration" "slack_integration" {
  organization = var.sentry_organization

  provider_key = "slack"
  name         = var.slack_organization_name
}

resource "sentry_issue_alert" "sentry_issue_alert" {
  organization = var.sentry_organization
  project      = "${var.environment}-${var.lambda_name}"
  name         = "Send a notification for new and repeated issues"

  action_match = "any"
  filter_match = "any"
  frequency    = 1440

  conditions = [
    # A new issue is created
    {
      id = "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"
    },
    # The issue is seen more than 10 times in one hour
    {
      id             = "sentry.rules.conditions.event_frequency.EventFrequencyCondition"
      value          = 10
      comparisonType = "count"
      interval       = "1h"
    },
    # The issue is seen more than 100 times in one day
    {
      id             = "sentry.rules.conditions.event_frequency.EventFrequencyCondition"
      value          = 100
      comparisonType = "count"
      interval       = "1d"
    },
    # The issue is seen more than 1000 times in one week
    {
      id             = "sentry.rules.conditions.event_frequency.EventFrequencyCondition"
      value          = 1000
      comparisonType = "count"
      interval       = "1w"
    },
  ]

  actions = [
    # Send a notification to the Slack workspace to #general
    {
      id         = "sentry.integrations.slack.notify_action.SlackNotifyServiceAction"
      channel    = var.slack_channel_name
      channel_id = var.slack_channel_id
      tags       = join(",", var.notification_tags)
      workspace  = data.sentry_organization_integration.slack_integration.internal_id
    },
  ]
}
