resource "azurerm_lb" "private" {
  count = local.privatelink_enabled ? 1 : 0

  name                = "${local.deployment_name}-private"
  location            = azurerm_resource_group.this.location
  resource_group_name = azurerm_resource_group.this.name
  sku                 = "Standard"
  tags                = local.tags

  frontend_ip_configuration {
    name                          = "services"
    subnet_id                     = azurerm_subnet.services.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azurerm_lb_backend_address_pool" "services" {
  count = local.privatelink_enabled ? 1 : 0

  name            = "services"
  loadbalancer_id = azurerm_lb.private[0].id
}

resource "azurerm_network_interface_backend_address_pool_association" "services" {
  count = local.privatelink_enabled ? 1 : 0

  network_interface_id    = azurerm_network_interface.services.id
  ip_configuration_name   = "primary"
  backend_address_pool_id = azurerm_lb_backend_address_pool.services[0].id
}

resource "azurerm_lb_probe" "services" {
  count = local.privatelink_enabled ? 1 : 0

  name            = "services"
  loadbalancer_id = azurerm_lb.private[0].id
  protocol        = "Tcp"
  port            = local.ports.mysql
}

resource "azurerm_lb_rule" "services" {
  for_each = local.privatelink_enabled ? {
    mysql           = local.ports.mysql
    kafka-anonymous = local.ports.kafka_pl_public
    kafka-sasl      = local.ports.kafka_pl_sasl
  } : {}

  name                           = each.key
  loadbalancer_id                = azurerm_lb.private[0].id
  frontend_ip_configuration_name = "services"
  backend_address_pool_ids       = [azurerm_lb_backend_address_pool.services[0].id]
  probe_id                       = azurerm_lb_probe.services[0].id
  protocol                       = "Tcp"
  frontend_port                  = each.value
  backend_port                   = each.value
  disable_outbound_snat          = true
}

resource "azurerm_private_link_service" "services" {
  count = local.privatelink_enabled ? 1 : 0

  name                                        = "${local.deployment_name}-services"
  location                                    = azurerm_resource_group.this.location
  resource_group_name                         = azurerm_resource_group.this.name
  load_balancer_frontend_ip_configuration_ids = [azurerm_lb.private[0].frontend_ip_configuration[0].id]
  visibility_subscription_ids                 = sort(tolist(var.private_link_subscription_ids))
  auto_approval_subscription_ids              = sort(tolist(var.private_link_subscription_ids))
  tags                                        = local.tags

  nat_ip_configuration {
    name                       = "primary"
    primary                    = true
    subnet_id                  = azurerm_subnet.private_link_service.id
    private_ip_address_version = "IPv4"
  }

  depends_on = [azurerm_lb_rule.services]
}
