locals {
  # VM definitions: name, node, vmid, static IP
  vms = {
    for idx, suffix in var.name_suffixes : "vm-${suffix}" => {
      name     = "${var.name_prefix}-${suffix}"
      node     = element(["mk33", "mk34", "mk39"], idx)
      vmid     = var.vmid_base + idx
      ipv4     = "${var.subnet_prefix}.30.${var.vmid_base + idx}/18"
    }
  }
}

resource "proxmox_virtual_environment_vm" "ubuntu_vm" {
  for_each = local.vms

  name      = each.value.name
  node_name = each.value.node
  vm_id     = each.value.vmid

  tags = concat(var.tags, [each.key])

  # ── CPU / Memory ──────────────────────────
  cpu {
    cores = var.cores
  }

  memory {
    dedicated = var.memory
  }

  # ── QEMU Guest Agent ──────────────────────
  agent {
    enabled = true
  }

  # ── Boot / EFI ────────────────────────────
  bios = "ovmf"

  efi_disk {
    datastore_id = var.storage
    type         = "4m"
  }

  machine = "q35"

  # ── SCSI Controller ───────────────────────
  scsi_hardware = "virtio-scsi-single"

  # ── Disk (Cloud-init image) ───────────────
  disk {
    datastore_id = var.storage
    file_id      = var.cloud_image_id
    interface    = "scsi0"
    iothread     = true
    discard      = "on"
    size         = var.disk_size
  }

  # ── Network ─────────────────────────────────
  network_device {
    bridge = var.bridge
  }

  # ── VGA / Console ─────────────────────────
  vga {
    type = "std"
  }

  # ── Cloud-Init ─────────────────────────────
  initialization {
    datastore_id = var.cloudinit_storage

    user_account {
      username = "jarvis"
      password = "ubuntu"
      keys     = [file(var.ssh_key_path)]
    }

    ip_config {
      ipv4 {
        address = each.value.ipv4
        gateway = var.gateway
      }
    }

    dns {
      servers = var.dns_servers
    }
  }
}
