{ config, lib, ... }:
let
  cfg = config.khscodes.openstack;
  openstackOutputInstanceModule = lib.khscodes.mkSubmodule {
    description = "Instance output";
    options = {
      id = lib.mkOption {
        type = lib.types.str;
        description = "ID of the instance, as a terraform string expression";
      };
      ipv4_address = lib.mkOption {
        type = lib.types.str;
        description = "IPv4 address of the instance, as a terraform string expression";
      };
      ipv6_address = lib.mkOption {
        type = lib.types.str;
        description = "IPv6 address of the instance, as a terraform string expression";
      };
      ipv6_external_gateway = lib.mkOption {
        type = lib.types.str;
        description = "The IPv6 external gateway for the network. This is useful to eg. create static routes in Unifi";
      };
      ipv6_cidr = lib.mkOption {
        type = lib.types.str;
        description = "IPv6 cidr";
      };
    };
  };
in
{
  options.khscodes.openstack = {
    output.compute_instance = lib.mkOption {
      type = lib.types.attrsOf openstackOutputInstanceModule;
      description = "Set by this module to be read by other modules when needing results of defining a compute instance";
      default = { };
    };
  };
  config = {
    khscodes.openstack.output.compute_instance = lib.attrsets.mapAttrs (
      name: value:
      (
        let
          sanitizedName = lib.khscodes.sanitize-terraform-name name;
        in
        {
          id = "\${ openstack_compute_instance_v2.${sanitizedName}.id }";
          ipv4_address = "\${ openstack_networking_floatingip_v2.${sanitizedName}.address }";
          ipv6_address = "\${ data.openstack_networking_port_v2.${sanitizedName}.all_fixed_ips[1] }";
          ipv6_external_gateway = "\${ [for ip in openstack_networking_router_v2.${sanitizedName}.external_fixed_ip : ip.ip_address if replace(ip.ip_address, \":\", \"\") != ip.ip_address][0] }";
          ipv6_cidr = "\${ openstack_networking_subnet_v2.${sanitizedName}_ip6.cidr }";
        }
      )
    ) cfg.compute_instance;
  };
}
