# S3 bucket
data "aws_s3_bucket" "qa_orcd_bucket" {
  bucket = "${var.environment}-orcdbucket"
}

# SQS queue
data "aws_sqs_queue" "qa_notifications_queue" {
  name = "${var.environment}-notifications"
}

# Integration test access policy document
data "aws_iam_policy_document" "integration_test_access_policy" {

  # SQS access policy
  statement {
    effect = "Allow"

    resources = [
      data.aws_sqs_queue.qa_notifications_queue.arn
    ]

    actions = [
      "sqs:SendMessage"
    ]
  }

  # List S3 objects
  statement {
    effect = "Allow"

    resources = [
      data.aws_s3_bucket.qa_orcd_bucket.arn
    ]

    condition {
      test     = "StringLike"
      variable = "s3:prefix"
      values = [
        "ows-notifications/emails",
        "ows-notifications/emails/*"
      ]
    }

    actions = [
      "s3:ListBucket"
    ]
  }

  # Get and delete S3 objects
  statement {
    effect = "Allow"

    resources = [
      "${data.aws_s3_bucket.qa_orcd_bucket.arn}/ows-notifications/emails/*"
    ]

    actions = [
      "s3:GetObject",
      "s3:DeleteObject"
    ]
  }
}


# Assume role policy document used by Jenkins
data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-pipeline-agent",
      ]
    }
  }
}


# SQS queue access policy
resource "aws_iam_policy" "integration_test_access_policy" {
  name   = "${var.environment}-${var.service_name}-integration-test-access-policy"
  policy = data.aws_iam_policy_document.integration_test_access_policy.json
}


# Assume role policy used by Jenkins
resource "aws_iam_role" "jenkins_invoke_role" {
  name               = "${var.environment}-${var.service_name}-integration-test-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}


# Attach policy to role
resource "aws_iam_role_policy_attachment" "policy_attachment" {
  role       = aws_iam_role.jenkins_invoke_role.id
  policy_arn = aws_iam_policy.integration_test_access_policy.arn
}
