data "aws_iam_policy_document" "datatheorem_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${var.datatheorem_aws_account_id}:root"]
    }

    condition {
      test     = "StringEquals"
      variable = "sts:ExternalId"

      values = [
        var.datatheorem_aws_external_id
      ]
    }
  }
}

data "aws_iam_policy_document" "datatheorem_policy_document" {
  statement {
    actions = [
      "apigateway:GET",
    ]

    resources = ["*"]
  }
}

resource "aws_iam_role" "datatheorem_role" {
  name               = "${var.environment}-${var.service_name}"
  assume_role_policy = data.aws_iam_policy_document.datatheorem_assume_role_policy.json
}

resource "aws_iam_policy" "datatheorem_policy" {
  name   = "${var.environment}-${var.service_name}-role-policy"
  policy = data.aws_iam_policy_document.datatheorem_policy_document.json
}

resource "aws_iam_role_policy_attachment" "datatheorem_role_policy_attachment" {
  role       = aws_iam_role.datatheorem_role.id
  policy_arn = aws_iam_policy.datatheorem_policy.arn
}

resource "aws_iam_role_policy_attachment" "datatheorem_audit_policy_attachement" {
  role       = aws_iam_role.datatheorem_role.id
  policy_arn = "arn:aws:iam::aws:policy/SecurityAudit"
}
