resource "aws_iam_role" "client" {
  name               = "${var.name_prefix}-${var.name}"
  description        = var.description
  assume_role_policy = data.aws_iam_policy_document.this.json
  tags               = var.common_tags
}

data "aws_iam_policy_document" "this" {
  dynamic "statement" {
    for_each = toset(var.external_accounts)
    content {
      actions = ["sts:AssumeRole"]
      effect  = "Allow"
      principals {
        type        = "AWS"
        identifiers = ["arn:aws:iam::${statement.value["account_id"]}:${statement.value["iam_entity"]}"]
      }
      dynamic "condition" {
        for_each = lookup(statement.value, "external_id", "") == "" ? [] : toset([statement.value["external_id"]])
        content {
          test     = "StringEquals"
          variable = "sts:ExternalId"
          values   = [condition.value]
        }
      }
    }
  }
}

resource "aws_iam_role_policy_attachment" "attachments" {
  count      = length(var.policies_list)
  role       = aws_iam_role.client.id
  policy_arn = var.policies_list[count.index]
}
