# ──────────────────────────────────────────────────────────────
# Quark's Holo-Grid Ledger — App server (Caddy + Tongo + Valkey)
# ──────────────────────────────────────────────────────────────

# ── Persistent volume for Valkey data ───────────────────────

resource "hcloud_volume" "data" {
  count    = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  name     = "hologrid-data-${terraform.workspace}"
  size     = var.volume_size
  location = var.location
  format   = "ext4"
}

# ── App server ──────────────────────────────────────────────

resource "hcloud_server" "app" {
  count       = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  name        = "hologrid-app-${terraform.workspace}"
  server_type = var.app_server_type
  location    = var.location
  image       = "ubuntu-24.04"

  ssh_keys = [hcloud_ssh_key.deploy.id]

  firewall_ids = [hcloud_firewall.app[0].id]

  user_data = templatefile("${path.module}/cloud-init/app.yml", {
    ssh_public_key = var.ssh_public_key
    domain         = terraform.workspace == "production" ? var.domain : "staging.${var.domain}"
    volume_id      = hcloud_volume.data[0].id
  })

  labels = {
    role        = "app"
    environment = terraform.workspace
  }

  # Wait for the subnet to exist before creating the server
  depends_on = [hcloud_network_subnet.servers]
}

# ── Attach volume to the app server ─────────────────────────

resource "hcloud_volume_attachment" "data" {
  count     = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  volume_id = hcloud_volume.data[0].id
  server_id = hcloud_server.app[0].id
  automount = true
}

# ── Private network attachment ──────────────────────────────

resource "hcloud_server_network" "app" {
  count      = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  server_id  = hcloud_server.app[0].id
  network_id = hcloud_network.internal[0].id
}
