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

  ntfyConfig = {
    services = {
      ntfy-sh = {
        enable = true;
        # environmentFile = "/run/.env";
        settings = {
          base-url = "https://${cfg.reverseProxy.subdomain}.mjallen.dev";
          enable-login = true;
          listen-http = ":${toString cfg.port}";
          cache-file = "${cfg.dataDir}/cache.db";
          attachment-cache-dir = "/${cfg.dataDir}/attachments";
          behind-proxy = true;
          auth-default-access = "deny-all";
          auth-file = "${cfg.dataDir}/user.db";
          auth-users = [
            "mjallen:$2a$10$g4TqI8UiKKVaKTmrwnXIw.wtajiLBM6oc3UCfJ//lPZFilJnBirn.:admin"
          ];
        };
      };
    };

    systemd.services = {
      ntfy-sh = {
        serviceConfig = {
          WorkingDirectory = lib.mkForce cfg.dataDir;
          StateDirectory = lib.mkForce cfg.dataDir;
          StateDirectoryMode = lib.mkForce 700;
          DynamicUser = lib.mkForce false;
          ProtectSystem = lib.mkForce null;
        };
      };
    };

    users.users.ntfy-sh = {
      isSystemUser = true;
      group = "ntfy-sh";
      home = cfg.dataDir;
    };
    users.groups.ntfy-sh = { };
  };

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

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

    port = mkOpt types.int 8008 "Port for ntfy 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 = lib.mkIf cfg.enable fullConfig;
}
