{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  cfg = config.${namespace}.services.paperless;

  paperlessPort = 28981;
  paperlessUserId = config.users.users.nix-apps.uid;
  paperlessGroupId = config.users.groups.jallen-nas.gid;
  paperlessPkg = pkgs.paperless-ngx;
in
{
  imports = [ ./options.nix ];

  config = mkIf cfg.enable {
    containers.paperless = {
      autoStart = true;
      privateNetwork = true;
      hostAddress = "10.0.1.3";
      localAddress = "10.0.1.20";
      hostAddress6 = "fc00::1";
      localAddress6 = "fc00::20";

      config =
        {
          lib,
          ...
        }:
        {
          # Enable paperless service
          services.paperless = {
            enable = false;
            package = paperlessPkg;
            port = paperlessPort;
            user = "paperless";
            address = "0.0.0.0";
            passwordFile = "/var/lib/paperless/paperless-password";
            # environmentFile = paperlessEnv; # unstable is too unstable, but this doesnt exist in stable.... disabling altogether....
          };

          # Create required users and groups
          users.groups = {
            documents = {
              gid = lib.mkForce paperlessGroupId;
            };
          };

          users.users.paperless = {
            isSystemUser = true;
            uid = lib.mkForce paperlessUserId;
            group = lib.mkForce "documents";
          };

          # Create and set permissions for required directories
          system.activationScripts.paperless-dirs = ''
            mkdir -p /var/lib/paperless

            chown -R paperless:documents /var/lib/paperless

            chmod -R 775 /var/lib/paperless

          '';

          networking = {
            firewall = {
              enable = true;
              allowedTCPPorts = [ paperlessPort ];
            };
            # Use systemd-resolved inside the container
            # Workaround for bug https://github.com/NixOS/nixpkgs/issues/162686
            useHostResolvConf = lib.mkForce false;
          };

          services.resolved.enable = true;
          system.stateVersion = "23.11";
        };

      # Bind mount directories from host
      bindMounts = {
        "/var/lib/paperless" = {
          hostPath = "/media/nas/main/nix-app-data/paperless";
          isReadOnly = false;
        };
        secrets = {
          hostPath = "/run/secrets/jallen-nas/paperless";
          isReadOnly = true;
          mountPoint = "/run/secrets/jallen-nas/paperless";
        };
        secret-env = {
          hostPath = "/run/secrets/rendered/paperless.env";
          isReadOnly = true;
          mountPoint = "/run/secrets/rendered/paperless.env";
        };
      };
    };

    networking.nat = {
      forwardPorts = [
        {
          destination = "10.0.1.20:28981";
          sourcePort = paperlessPort;
        }
      ];
    };
  };
}
