locals {
  # Generate a list of VMIDs from vmid_base to vmid_base + lxc_count - 1
  vmids = [for i in range(var.lxc_count) : var.vmid_base + i]

  # Derive IPv4 from each VMID: subnet_prefix + first2digits + last2digits
  # e.g. vmid 5052 -> 192.168.50.52/18
  ipv4s = {
    for vmid in local.vmids :
    vmid => "${var.subnet_prefix}.${floor(vmid / 100) % 100}.${vmid % 100}/18"
  }

  # Derive hostnames: name_prefix + vmid
  hostnames = {
    for vmid in local.vmids :
    vmid => "${var.name_prefix}-${vmid}"
  }
}

module "lxc" {
  source = "./modules/lxc"

  for_each = toset([for v in local.vmids : tostring(v)])

  vmid     = tonumber(each.key)
  hostname = local.hostnames[tonumber(each.key)]
  ipv4     = local.ipv4s[tonumber(each.key)]

  node          = var.node
  cores         = var.cores
  memory        = var.memory
  storage       = var.storage
  rootfs_size   = var.rootfs_size
  gateway       = var.gateway
  dns_servers   = var.dns_servers
  ssh_key_path  = var.ssh_key_path
  template_file_id = var.template_file_id
  password      = var.password
  tags          = concat(var.tags, ["vmid-${each.key}"])
  unprivileged  = var.unprivileged
  devices       = var.devices
}
