# ──────────────────────────────────────────────────────────────
# Quark's Holo-Grid Ledger — SSH key, network & firewalls
# ──────────────────────────────────────────────────────────────

# ── SSH key ──────────────────────────────────────────────────

resource "hcloud_ssh_key" "deploy" {
  name       = "hologrid-deploy-${terraform.workspace}"
  public_key = var.ssh_public_key
}

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

resource "hcloud_network" "internal" {
  count    = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  name     = "hologrid-internal-${terraform.workspace}"
  ip_range = "10.0.0.0/16"
}

resource "hcloud_network_subnet" "servers" {
  count        = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  network_id   = hcloud_network.internal[0].id
  type         = "cloud"
  network_zone = "eu-central"
  ip_range     = "10.0.1.0/24"
}

# ── Firewall: Forgejo server ────────────────────────────────

resource "hcloud_firewall" "forgejo" {
  count = terraform.workspace == "tooling" ? 1 : 0
  name  = "hologrid-forgejo"

  # SSH (Host OS)
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "22"
    source_ips = ["0.0.0.0/0", "::/0"]
  }

  # Forgejo SSH (Git pushes)
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "2222"
    source_ips = ["0.0.0.0/0", "::/0"]
  }

  # HTTP
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "80"
    source_ips = ["0.0.0.0/0", "::/0"]
  }

  # HTTPS
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "443"
    source_ips = ["0.0.0.0/0", "::/0"]
  }

  # Forgejo Web UI
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "3000"
    source_ips = ["0.0.0.0/0", "::/0"]
  }
}

# ── Firewall: App server ────────────────────────────────────

resource "hcloud_firewall" "app" {
  count = (terraform.workspace == "staging" || terraform.workspace == "production") ? 1 : 0
  name  = "hologrid-app-${terraform.workspace}"

  # SSH
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "22"
    source_ips = ["0.0.0.0/0", "::/0"]
  }

  # HTTP
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "80"
    source_ips = ["0.0.0.0/0", "::/0"]
  }

  # HTTPS
  rule {
    direction  = "in"
    protocol   = "tcp"
    port       = "443"
    source_ips = ["0.0.0.0/0", "::/0"]
  }
}
