locals {
  projects = {
    "ama-backend" = {
      name     = "ama-backend"
      slug     = "ama-backend"
      platform = "node"
    },
    "ama-frontend" = {
      name     = "ama-frontend"
      slug     = "ama-frontend"
      platform = "javascript-react"
    }
    "rti_user_preferences_service" = {
      name     = "user-preferences"
      slug     = "user-preferences"
      platform = "node"
    },
    "rti_notifications_worker" = {
      name     = "notifications-worker"
      slug     = "notifications-worker"
      platform = "node"
    },
  }
}

resource "sentry_project" "ama_project" {
  for_each = local.projects

  organization = "gdb"
  team         = sentry_team.ama.id
  name         = each.value["name"]
  slug         = each.value["slug"]
  platform     = each.value["platform"]
}

resource "sentry_rule" "ama_backend_default_rules" {
  for_each = local.projects

  organization = "gdb"
  project      = each.value["slug"]
  name         = "Send a notification for new issues"
  action_match = "any"
  frequency    = 60

  conditions = [
    {
      id   = "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"
      name = "An issue is first seen"
    }
  ]

  actions = [
    {
      id   = "sentry.rules.actions.notify_event.NotifyEventAction"
      name = "Send a notification"
    }
  ]
}

resource "sentry_rule" "ama_backend_prod_rule" {
  organization = "gdb"
  project      = sentry_project.ama_project["ama-backend"].slug
  name         = "Send a notification for new and repeated issues"
  action_match = "any"
  frequency    = 60
  environment  = "production"

  conditions = module.alert_conditions.this

  actions = [
    merge(
      local.slack_action,
      {
        tags = "environment,user"
      }
    )
  ]
}

resource "sentry_rule" "ama_frontend_prod_rule" {
  organization = "gdb"
  project      = sentry_project.ama_project["ama-frontend"].slug
  name         = "Send a notification for new and repeated issues"
  action_match = "any"
  frequency    = 60
  environment  = "production"

  conditions = module.alert_conditions.this

  actions = [
    merge(
      local.slack_action,
      {
        tags = "environment,os,expoAppVersion,device,deviceId,level"
      }
    )
  ]
}

resource "sentry_rule" "rti_user_preferences_service_prod_rule" {
  organization = "gdb"
  project      = sentry_project.ama_project["rti_user_preferences_service"].slug
  name         = "Send a notification for new and repeated issues"
  action_match = "any"
  frequency    = 60
  environment  = "production"

  conditions = module.alert_conditions.this

  actions = [
    merge(
      local.slack_action,
      {
        tags = "environment"
      }
    )
  ]
}
