module "graphql_nr_build_secrets_manager_policy" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/secretsmanager/secrets_list?ref=0.3.0"

  secrets = [
    "${var.environment}/${var.service_name}/KSQL_CREDS",
    "${var.environment}/${var.service_name}/SFORCE_REFRESH_TOKEN",
    "${var.environment}/${var.service_name}/SFORCE_CLIENT_ID",
    "${var.environment}/${var.service_name}/SFORCE_CLIENT_SECRET",
    // these integration test secrets are created/managed in the integration-test sub-folder
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_NO_ROLE",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_CONTRIBUTION_VIEWONLY",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_CONTRIBUTION_VIEWCREATE",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_CONTRIBUTION_VIEWCREATEMANAGE",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_CONTRIBUTION_VIEWCREATEMANAGEDELETE",
    "${var.environment}/${var.service_name}-integration-test/AUTH0_TEST_APP_CLIENT_ID",
    "${var.environment}/${var.service_name}-integration-test/AUTH0_TEST_APP_CLIENT_SECRET",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_SOUND_RECORDING_VIEWONLY",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_SOUND_RECORDING_VIEWCREATE",
    "${var.environment}/${var.service_name}-integration-test/GRAPHQL_TEST_NR_IDENTITY_SOUND_RECORDING_VIEWCREATEMANAGE",
  ]
  action_types = ["read"]
  depends_on = [
    module.secrets
  ]
}

resource "aws_iam_policy" "graphql_nr_build_secrets_manager_policy" {
  name   = "SecretsManager-${var.environment}-${var.service_name}-integration-test-policy"
  policy = module.graphql_nr_build_secrets_manager_policy.policy.json
}

data "aws_iam_policy_document" "jenkins_assume_role_policy" {
  version = "2012-10-17"
  statement {
    actions = ["sts:AssumeRole"]
    effect  = "Allow"
    principals {
      type = "AWS"

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

resource "aws_iam_role" "graphql_nr_build_role" {
  name = "${var.environment}-${var.service_name}-integration-test-role"

  assume_role_policy = data.aws_iam_policy_document.jenkins_assume_role_policy.json
}

resource "aws_iam_role_policy_attachment" "graphql_nr_build_role_policy_attachment" {
  role       = aws_iam_role.graphql_nr_build_role.name
  policy_arn = aws_iam_policy.graphql_nr_build_secrets_manager_policy.arn
}
