# {{ project_name }} - Hetzner Cloud Provider Configuration
# Generated by typedialog-prov-gen

terraform {
  required_providers {
    hcloud = {
      source  = "hetznercloud/hcloud"
      version = "~> 1.44"
    }
  }
}

provider "hcloud" {
  token = var.hetzner_token
}

# Hetzner-specific variables
variable "hetzner_token" {
  description = "Hetzner Cloud API token"
  type        = string
  sensitive   = true
}

variable "hetzner_server_type" {
  description = "Hetzner server type (cx11, cx21, cx31, etc.)"
  type        = string
  default     = "cx11"  # 1 vCPU, 2GB RAM
}

variable "hetzner_location" {
  description = "Hetzner datacenter location"
  type        = string
  default     = "{{ infrastructure.hetzner_location | default(value="nbg1") }}"

  validation {
    condition     = contains(["nbg1", "fsn1", "hel1", "ash"], var.hetzner_location)
    error_message = "Location must be nbg1 (Nuremberg), fsn1 (Falkenstein), hel1 (Helsinki), or ash (Ashburn)."
  }
}

# SSH key for Hetzner instances
resource "hcloud_ssh_key" "default" {
  name       = "${local.project_name}-${local.environment}"
  public_key = file("~/.ssh/id_ed25519.pub")
}

# Hetzner server instance
resource "hcloud_server" "app" {
  name        = "${local.project_name}-${local.environment}-app"
  server_type = var.hetzner_server_type
  location    = var.hetzner_location
  image       = "ubuntu-22.04"

  ssh_keys = [hcloud_ssh_key.default.id]

  labels = local.common_tags

  user_data = templatefile("${path.module}/../../scripts/cloud-init.yml", {
    project_name = local.project_name
    environment  = local.environment
  })
}

# Hetzner firewall
resource "hcloud_firewall" "app" {
  name = "${local.project_name}-${local.environment}-firewall"

  rule {
    direction = "in"
    protocol  = "tcp"
    port      = "22"
    source_ips = var.allowed_ips
  }

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

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

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

output "hetzner_server_ip" {
  description = "Hetzner server public IP"
  value       = hcloud_server.app.ipv4_address
}

output "hetzner_server_id" {
  description = "Hetzner server ID"
  value       = hcloud_server.app.id
}
