{ lib, config, ... }:
let
  cfg = config.khscodes.unifi;
  unifiStaticRouteModule = lib.khscodes.mkSubmodule {
    description = "Unifi static route";
    options = {
      network = lib.mkOption {
        type = lib.types.str;
        description = "The network to make a static route for";
      };
      name = lib.mkOption {
        type = lib.types.str;
        description = "Human friendly name of the static route";
      };
      distance = lib.mkOption {
        type = lib.types.int;
        description = "The distance of the hop";
      };
      next_hop = lib.mkOption {
        type = lib.types.str;
        description = "The router that can route the network";
      };
    };
  };
in
{
  options.khscodes.unifi = {
    enable = lib.mkEnableOption "Enables the unifi provider";
    static_route = lib.mkOption {
      type = lib.types.attrsOf unifiStaticRouteModule;
      description = "Static routes";
    };
  };

  imports = [ ./output.nix ];

  config = lib.mkIf cfg.enable {
    terraform.required_providers.unifi = {
      source = "paultyng/unifi";
      version = "= 0.42.0-prerelease";
    };
    provider.unifi = {
      allow_insecure = true;
    };

    resource.unifi_static_route = lib.mapAttrs' (
      name: value:
      let
        sanitizedName = lib.khscodes.sanitize-terraform-name name;
      in
      {
        name = sanitizedName;
        value = {
          inherit (value)
            network
            name
            distance
            next_hop
            ;
          type = "nexthop-route";
        };
      }
    ) cfg.static_route;
  };
}
