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

resource "hcloud_server" "app" {
  name               = "iklim-app-01"
  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.test_spread.id

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

  # prevent_destroy: Terraform'un sunucuyu kazara silmesini engeller.
  # Kasitli silmek icin once bu bloku kaldir.
  lifecycle {
    prevent_destroy = true
  }
}

resource "hcloud_server" "db" {
  name               = "iklim-db-01"
  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.test_spread.id

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

  lifecycle {
    prevent_destroy = true
  }
}

# Ayri resource: firewall veya network degistiginde sunucu recreation tetiklenmez.
resource "hcloud_server_network" "app" {
  server_id  = hcloud_server.app.id
  network_id = hcloud_network.main.id
  ip         = local.app_private_ip

  depends_on = [hcloud_network_subnet.app]
}

resource "hcloud_server_network" "db" {
  server_id  = hcloud_server.db.id
  network_id = hcloud_network.main.id
  ip         = local.db_private_ip

  depends_on = [hcloud_network_subnet.db]
}

resource "hcloud_firewall_attachment" "app" {
  firewall_id = hcloud_firewall.app.id
  server_ids  = [hcloud_server.app.id]
}

resource "hcloud_firewall_attachment" "db" {
  firewall_id = hcloud_firewall.db.id
  server_ids  = [hcloud_server.db.id]
}
