data "aws_ec2_managed_prefix_lists" "private_subnets" {
  tags = {
    environment  = var.env
    subnet_group = "all"
    tier         = "private"
    vpc_id       = var.vpc_id
  }
}

data "aws_ec2_managed_prefix_list" "private_subnets" {
  id = one(data.aws_ec2_managed_prefix_lists.private_subnets.ids)
}

data "aws_ec2_managed_prefix_lists" "https_allowed_custom_prefix_list" {
  filter {
    name   = "prefix-list-name"
    values = local.https_allowed_prefix_list_names
  }
}

# Security group for cluster
resource "aws_security_group" "elasticsearch_security_group" {
  count       = length(var.custom_security_group_ids) > 0 ? 0 : 1
  name        = "${var.env}-${var.aws_es_domain_name}-elasticsearch-security-group"
  description = "Elasticsearch security group for ${var.env}-${var.aws_es_domain_name}"
  vpc_id      = var.vpc_id

  tags = merge(local.combined_resource_tags, local.primsa_sg_exception_tags)
}

resource "aws_security_group_rule" "allow_https_inbound" {
  count             = length(var.custom_security_group_ids) > 0 ? 0 : 1
  type              = "ingress"
  from_port         = 443
  to_port           = 443
  protocol          = "TCP"
  cidr_blocks       = local.https_allowed_custom_cidr_blocks[var.env]
  prefix_list_ids   = data.aws_ec2_managed_prefix_lists.https_allowed_custom_prefix_list.ids
  security_group_id = aws_security_group.elasticsearch_security_group[0].id
}
