{ khscodesLib, ... }:
{ config, lib, ... }:
let
  cfg = config.khscodes.hcloud;
  hcloudOutputServerModule = khscodesLib.mkSubmodule {
    description = "Module defined when a corresponding server has been defined";
    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";
      };
    };
  };
  hcloudDataOutputSshKeyModule = khscodesLib.mkSubmodule {
    description = "Module defined when a corresponding ssh key has ben retrieved";
    options = {
      id = lib.mkOption {
        type = lib.types.str;
        description = "ID of the ssh key, as a terraform string expression";
      };
    };
  };
in
{
  options.khscodes.hcloud = {
    output.server = lib.mkOption {
      type = lib.types.attrsOf hcloudOutputServerModule;
      description = "Set by this module to be read by other modules when needing results of defining a server";
      default = { };
    };
    output.data.ssh_key = lib.mkOption {
      type = lib.types.attrsOf hcloudDataOutputSshKeyModule;
      description = "Set by this module to be read by other modules when needing the result of the ssh key";
      default = { };
    };
  };
  config = {
    khscodes.hcloud.output.server = lib.attrsets.mapAttrs (
      name: value:
      (
        let
          sanitizedName = khscodesLib.sanitize-terraform-name name;
        in
        {
          id = "\${ hcloud_server.${sanitizedName}.id }";
          ipv4_address = "\${ hcloud_server.${sanitizedName}.ipv4_address }";
          ipv6_address = "\${ hcloud_server.${sanitizedName}.ipv6_address }";
        }
      )
    ) cfg.server;
    khscodes.hcloud.output.data.ssh_key = lib.attrsets.mapAttrs (
      name: _:
      let
        sanitizedName = khscodesLib.sanitize-terraform-name name;
      in
      {
        id = "\${ data.hcloud_ssh_key.${sanitizedName}.id }";
      }
    ) cfg.data.ssh_key;
  };
}
