provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "dev-orcd-terraform-state"
    key     = "dev/kafka-infra/elasticsearch-sink/indices/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

terraform {
  required_providers {
    elasticsearch = {
      source  = "phillbaker/elasticsearch"
      version = "2.0.7"
    }
    aws = {
      source = "hashicorp/aws"
    }
  }
}

data "aws_caller_identity" "current" {}

# If you need to run this locally, add a principal to this trust policy
data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::${data.aws_caller_identity.current.account_id}:role/cross-account-atlantis-role",
      ]
    }
  }
}

# Role exclusively used for creating Elasticsearch indices
resource "aws_iam_role" "es_index_role" {
  name               = "${var.environment}-es-index-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
}

provider "elasticsearch" {
  url                   = var.elasticsearch_url
  healthcheck           = false
  elasticsearch_version = "7.9"
  aws_assume_role_arn   = aws_iam_role.es_index_role.arn
}

resource "elasticsearch_index" "labelParticipant" {
  name               = "label_participant_v01"
  number_of_shards   = 3
  number_of_replicas = 1
  refresh_interval   = "60s"
  force_destroy      = true

  mappings = jsonencode({
    "properties" : {
      "uuid" : {
        "type" : "keyword"
      },
      "name" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "keyword",
            "ignore_above" : 256
          }
        }
      },
      "id" : {
        "type" : "keyword"
      },
      "subaccountId" : {
        "type" : "keyword"
      },
      "vendorId" : {
        "type" : "keyword"
      }
    }
  })
}
