data "aws_caller_identity" "current" {}

locals {
  account_id = var.aws_account_number == "" ? data.aws_caller_identity.current.account_id : var.aws_account_number
}

data "aws_iam_policy_document" "owsrequest_data" {
  statement {
    effect = "Allow"

    actions = [
      "dynamodb:GetItem",
    ]

    resources = [
      "arn:aws:dynamodb:${var.aws_region}:${local.account_id}:table/${var.environment_name}-ows-request-authorization",
    ]

    condition {
      test     = "ForAllValues:StringLike"
      variable = "dynamodb:LeadingKeys"

      values = [
        "${var.service_name}:*",
      ]
    }
  }

  statement {
    effect = "Allow"

    actions = [
      "dynamodb:PutItem",
    ]

    resources = [
      "arn:aws:dynamodb:${var.aws_region}:${local.account_id}:table/${var.environment_name}-ows-request-authorization",
    ]

    condition {
      test     = "ForAllValues:StringNotLike"
      variable = "dynamodb:LeadingKeys"

      values = [
        "${var.service_name}:*",
      ]
    }
  }
}

resource "aws_iam_policy" "owsrequest_policy" {
  name        = "Dynamo-${var.environment_name}-${var.service_name}-owsrequest"
  description = var.policy_description
  policy      = data.aws_iam_policy_document.owsrequest_data.json
}

