{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  inherit (lib.${namespace}) mkOpt mkReverseProxyOpt;
  cfg = config.${namespace}.services.headscale;

  headscaleConfig = {
    services.headscale = {
      enable = true;
      address = "0.0.0.0";
      port = cfg.port;
      settings = {
        server_url = "https://headscale.mjallen.dev:443";
        database.sqlite.path = "${cfg.dataDir}/db.sqlite";
        dns = {
          nameservers.global = [
            "1.1.1.1"
            "8.8.8.8"
          ];
          base_domain = "tailnet.mjallen.dev";
          magic_dns = true;
        };
      };
      # oidc
    };
  };

  # Create reverse proxy configuration using mkReverseProxy
  reverseProxyConfig = lib.${namespace}.mkReverseProxy {
    name = "headscale";
    subdomain = cfg.reverseProxy.subdomain;
    url = "http://${cfg.localAddress}:${toString cfg.port}";
    middlewares = cfg.reverseProxy.middlewares;
  };

  fullConfig = {
    "${namespace}".services.traefik = lib.mkIf cfg.reverseProxy.enable {
      reverseProxies = [ reverseProxyConfig ];
    };
  }
  // headscaleConfig;
in
{
  options.${namespace}.services.headscale = {
    enable = mkEnableOption "headscale service";

    port = mkOpt types.int 8080 "Port for headscale to be hosted on";

    localAddress = mkOpt types.str "127.0.0.1" "local address of the service";

    dataDir = mkOpt types.str "" "Path to the data dir";

    reverseProxy = mkReverseProxyOpt;
  };

  config = mkIf cfg.enable fullConfig;
}
