
data "aws_iam_policy_document" "this_queue_policy" {
  version = "2012-10-17"

  statement {
    actions = [
      "sqs:SendMessage"
    ]

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"

      values = [
        module.this_topic.topic.arn
      ]
    }

    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = ["*"]
    }

    resources = [
      module.this_queue.queue.arn,
    ]

    sid = "__default_statement_ID"
  }
}

module "this_queue" {
  source = "../sqs/"

  name_prefix                = var.name_prefix
  name                       = var.name
  visibility_timeout_seconds = 60
  receive_wait_time_seconds  = 0

  common_tags = merge(
    var.common_tags,
    {
      service                  = "SQS",
      plat_env_project_service = "${var.aggregated_tag}_PRL_SQS"
    }
  )
}

resource "aws_sqs_queue_policy" "this" {
  policy    = data.aws_iam_policy_document.this_queue_policy.json
  queue_url = module.this_queue.queue.id
}

data "aws_iam_policy_document" "this_topic_policy" {
  policy_id = "__default_policy_ID"

  statement {
    actions = [
      "SNS:Publish",
    ]

    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"

      values = [
        "arn:aws:cloudwatch:${var.aws_region_id}:${var.account_id}:alarm:*",
      ]
    }

    effect = "Allow"

    principals {
      type        = "AWS"
      identifiers = ["*"]
    }

    resources = [
      module.this_topic.topic.arn,
    ]

    sid = "__default_statement_ID"
  }
}

module "this_topic" {
  source = "../sns/topic"

  name = "${var.name_prefix}-${var.name}"

  common_tags = merge(
    var.common_tags,
    {
      service                  = "SNS",
      plat_env_project_service = "${var.aggregated_tag}_PRL_SNS"
    }
  )
}

resource "aws_sns_topic_policy" "this_topic_policy" {
  arn    = module.this_topic.topic.arn
  policy = data.aws_iam_policy_document.this_topic_policy.json
}

resource "aws_sns_topic_subscription" "lmabda_failures_sns_sqs" {
  topic_arn = module.this_topic.topic.arn
  protocol  = "sqs"
  endpoint  = module.this_queue.queue.arn
}
