terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}

data "aws_iam_policy_document" "lambda_role" {
  version = "2012-10-17"
  statement {
    actions = ["sts:AssumeRole"]
    effect  = "Allow"
    principals {
      type        = "AWS"
      identifiers = [var.assumer]
    }
  }
}

resource "aws_iam_role" "this" {
  name               = "${var.name_prefix}-${var.name}_role"
  assume_role_policy = data.aws_iam_policy_document.lambda_role.json
  tags               = var.tags
}

data "aws_iam_policy_document" "policy" {
  statement {
    actions = concat([
      "ce:GetCostAndUsage",
      ],
      !var.quicksight_permissions ? [] : [
        "quicksight:ListDataSets",
        "quicksight:CreateIngestion",
        "quicksight:DescribeIngestion",
    ])
    resources = ["*"]
  }

}

resource "aws_iam_policy" "this" {
  name   = "${var.name_prefix}-${var.name}_policy"
  policy = data.aws_iam_policy_document.policy.json
}

resource "aws_iam_role_policy_attachment" "this" {
  role       = aws_iam_role.this.id
  policy_arn = aws_iam_policy.this.arn
}
