resource "hcloud_ssh_key" "admin" {
  name       = "${local.name_prefix}-admin-key"
  public_key = file(var.admin_ssh_public_key_path)
}

resource "hcloud_server" "app" {
  for_each = local.app_private_ips

  name               = each.key
  server_type        = var.server_type_app
  image              = var.image
  location           = var.location
  ssh_keys           = [hcloud_ssh_key.admin.id]
  placement_group_id = hcloud_placement_group.app_spread.id

  labels = {
    environment = local.environment
    role        = "app"
    type        = "service"
  }

  lifecycle {
    prevent_destroy = true
  }
}

resource "hcloud_server" "db" {
  for_each = local.db_private_ips

  name               = each.key
  server_type        = var.server_type_db
  image              = var.image
  location           = var.location
  ssh_keys           = [hcloud_ssh_key.admin.id]
  placement_group_id = hcloud_placement_group.db_spread.id

  labels = {
    environment = local.environment
    role        = "db"
    type        = "db"
  }

  lifecycle {
    prevent_destroy = true
  }
}

resource "hcloud_server_network" "app" {
  for_each = local.app_private_ips

  server_id  = hcloud_server.app[each.key].id
  network_id = hcloud_network.main.id
  ip         = each.value

  depends_on = [hcloud_network_subnet.app]
}

resource "hcloud_server_network" "db" {
  for_each = local.db_private_ips

  server_id  = hcloud_server.db[each.key].id
  network_id = hcloud_network.main.id
  ip         = each.value

  depends_on = [hcloud_network_subnet.db]
}

resource "hcloud_firewall_attachment" "app" {
  firewall_id = hcloud_firewall.app.id
  server_ids  = [for s in hcloud_server.app : s.id]
}

resource "hcloud_firewall_attachment" "db" {
  firewall_id = hcloud_firewall.db.id
  server_ids  = [for s in hcloud_server.db : s.id]
}
