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

  ntfyEnvFile = config.sops.secrets."jallen-nas/ntfy/auth-users".path;

  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 = "/var/lib/ntfy-sh/cache.db";
          attachment-cache-dir = "/var/lib/ntfy-sh/attachments";
          behind-proxy = true;
          auth-default-access = "deny-all";
          auth-file = "/var/lib/ntfy-sh/user.db";
          auth-users = [
            "mjallen:$2a$10$g4TqI8UiKKVaKTmrwnXIw.wtajiLBM6oc3UCfJ//lPZFilJnBirn.:admin"
          ];
        };
      };
    };
    # Create and set permissions for required directories
    system.activationScripts.ntfy-dirs = ''
      mkdir -p /var/lib/ntfy-sh

      chown -R ntfy-sh:ntfy-sh /var/lib/ntfy-sh

      chmod -R 775 /var/lib/ntfy-sh
    '';
  };

  bindMounts = {
    "/var/lib/ntfy-sh" = {
      hostPath = cfg.dataDir;
      isReadOnly = false;
    };
    "/run/.env" = {
      hostPath = ntfyEnvFile;
      isReadOnly = true;
    };
  };

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

  ntfyContainer =
    (lib.${namespace}.mkContainer {
      name = "ntfy";
      localAddress = cfg.localAddress;
      ports = [ cfg.port ];
      bindMounts = bindMounts;
      config = ntfyConfig;
    })
      { inherit lib; };

  fullConfig = {
    ${namespace}.services.traefik = lib.mkIf cfg.reverseProxy.enable {
      reverseProxies = [ reverseProxyConfig ];
    };
  }
  // ntfyContainer;
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;
}
